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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import { parseStrictNonNegativeInteger } from "@openclaw/normalization-core/number-coercion";
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import { resolveSessionStableReplyMode } from "../../auto-reply/reply/session-stable-reply-mode.js";
import { isSyntheticSourceReplyTurn } from "../../auto-reply/reply/source-reply-delivery-mode.js";
import {
  formatThinkingLevels,
  normalizeThinkLevel,
  normalizeVerboseLevel,
} from "../../auto-reply/thinking.js";
import { formatCliCommand } from "../../cli/command-format.js";
import type { InternalSessionEntry } from "../../config/sessions/types.js";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { resolveAgentExplicitRecipientSession } from "../../infra/outbound/agent-delivery.js";
import { buildOutboundSessionContext } from "../../infra/outbound/session-context.js";
import { resolvePluginMetadataSnapshot } from "../../plugins/plugin-metadata-snapshot.js";
import {
  classifySessionKeyShape,
  isUnscopedSessionKeySentinel,
  normalizeAgentId,
  resolveAgentIdFromSessionKey,
} from "../../routing/session-key.js";
import type { RuntimeEnv } from "../../runtime.js";
import {
  AGENT_HARNESS_MODEL_RUN_FORBIDDEN_MESSAGE,
  resolveAgentHarnessSessionContextError,
} from "../../sessions/agent-harness-session-key.js";
import {
  assertAgentDatabaseAdmitted,
  evaluateAgentDatabaseAdmissions,
  hasAgentDatabaseAdmissions,
  recordAgentDatabaseAdmissions,
} from "../../state/agent-database-admission.js";
import { resolveUserPath } from "../../utils.js";
import { isDeliverableMessageChannel, resolveMessageChannel } from "../../utils/message-channel.js";
import { resolveAgentRuntimeConfig } from "../agent-runtime-config.js";
import { resolveAgentRunCwd } from "../agent-scope-config.js";
import {
  listAgentIds,
  resolveAgentDir,
  resolveSessionAgentId,
  resolveAgentWorkspaceDir,
} from "../agent-scope.js";
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from "../defaults.js";
import {
  resolveAcpPromptBody,
  prependInternalEventContext,
  resolveInternalEventTranscriptBody,
} from "../internal-events.js";
import { AGENT_LANE_SUBAGENT } from "../lanes.js";
import type { ModelManifestNormalizationContext } from "../model-ref-shared.js";
import { buildConfiguredModelCatalog, resolveConfiguredModelRef } from "../model-selection.js";
import type { PreparedModelRuntimePluginGeneration } from "../prepared-model-runtime.types.js";
import { normalizeSpawnedRunMetadata } from "../spawned-context.js";
import { resolveEffectiveAgentRuntime } from "../thinking-runtime.js";
import { resolveAgentTimeoutMs } from "../timeout.js";
import { ensureAgentWorkspace } from "../workspace.js";
import { acquireWorktreeRunLease, resolveWorktreeIdForPath } from "../worktrees/run-lease.js";
import { resolveExplicitAgentCommandSessionKey } from "./explicit-session-key.js";
import { loadAcpManagerRuntime } from "./runtime-loaders.js";
import { resolveSession } from "./session.js";
import type { AgentCommandOpts } from "./types.js";

const OVERRIDE_VALUE_MAX_LENGTH = 256;

function containsControlCharacters(value: string): boolean {
  for (const char of value) {
    const code = char.codePointAt(0);
    if (code === undefined) {
      continue;
    }
    if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
      return true;
    }
  }
  return false;
}

export function normalizeExplicitOverrideInput(raw: string, kind: "provider" | "model"): string {
  const trimmed = raw.trim();
  const label = kind === "provider" ? "Provider" : "Model";
  if (!trimmed) {
    throw new Error(`${label} override must be non-empty.`);
  }
  if (trimmed.length > OVERRIDE_VALUE_MAX_LENGTH) {
    throw new Error(`${label} override exceeds ${String(OVERRIDE_VALUE_MAX_LENGTH)} characters.`);
  }
  if (containsControlCharacters(trimmed)) {
    throw new Error(`${label} override contains invalid control characters.`);
  }
  return trimmed;
}

export type PreparedAgentCommandRuntimeContext = Readonly<{
  config: OpenClawConfig;
  pluginGeneration: PreparedModelRuntimePluginGeneration;
}>;

export async function prepareAgentCommandExecution(
  opts: AgentCommandOpts,
  runtime: RuntimeEnv,
  runtimeContext?: PreparedAgentCommandRuntimeContext,
) {
  const isRawModelRun = opts.modelRun === true || opts.promptMode === "none";
  const message = opts.message ?? "";
  if (!message.trim()) {
    throw new Error("Message (--message) is required");
  }
  const rawExplicitSessionKey = opts.sessionKey?.trim();
  const requestedSessionId = opts.sessionId?.trim() || undefined;
  const rawTo = opts.to?.trim();
  const toSessionKey =
    !rawExplicitSessionKey && !requestedSessionId && classifySessionKeyShape(rawTo) === "agent"
      ? rawTo
      : undefined;
  const recipientChannel = resolveMessageChannel(opts.channel);
  const shouldResolveExplicitRecipientSession = Boolean(
    !rawExplicitSessionKey &&
    !requestedSessionId &&
    !toSessionKey &&
    opts.agentId?.trim() &&
    recipientChannel &&
    isDeliverableMessageChannel(recipientChannel) &&
    rawTo,
  );
  if (!opts.to && !requestedSessionId && !rawExplicitSessionKey && !opts.agentId) {
    throw new Error(
      "Pass --to <E.164>, --session-key, --session-id, or --agent to choose a session",
    );
  }

  const cfg = await resolveAgentRuntimeConfig(runtime, {
    runtimeTargetsChannelSecrets: opts.deliver === true,
    runtimeChannelSecretScope:
      opts.deliver !== true && shouldResolveExplicitRecipientSession && recipientChannel
        ? { channel: recipientChannel, accountId: opts.accountId }
        : undefined,
  });
  const normalizedSpawned = normalizeSpawnedRunMetadata({
    spawnedBy: opts.spawnedBy,
    groupId: opts.groupId,
    groupChannel: opts.groupChannel,
    groupSpace: opts.groupSpace,
    workspaceDir: opts.workspaceDir,
  });
  const agentIdOverrideRaw = opts.agentId?.trim();
  const agentIdOverride = agentIdOverrideRaw ? normalizeAgentId(agentIdOverrideRaw) : undefined;
  if (agentIdOverride) {
    const knownAgents = listAgentIds(cfg);
    if (!knownAgents.includes(agentIdOverride)) {
      throw new Error(
        `Unknown agent id "${agentIdOverrideRaw}". Use "${formatCliCommand("openclaw agents list")}" to see configured agents.`,
      );
    }
  }
  const shouldScopeDefaultAgentKey = Boolean(
    rawExplicitSessionKey &&
    !agentIdOverride &&
    classifySessionKeyShape(rawExplicitSessionKey) === "legacy_or_alias" &&
    !isUnscopedSessionKeySentinel(rawExplicitSessionKey),
  );
  const explicitSessionKey =
    toSessionKey ??
    resolveExplicitAgentCommandSessionKey({
      rawExplicitSessionKey,
      agentIdOverride,
      shouldScopeDefaultAgentKey,
      cfg,
    });
  if (explicitSessionKey && classifySessionKeyShape(explicitSessionKey) === "malformed_agent") {
    throw new Error(
      `Invalid --session-key "${explicitSessionKey}". Agent-prefixed session keys must use agent:<agent-id>:<session-key>.`,
    );
  }
  if (
    agentIdOverride &&
    explicitSessionKey &&
    classifySessionKeyShape(explicitSessionKey) === "agent"
  ) {
    const sessionAgentId = resolveAgentIdFromSessionKey(explicitSessionKey);
    if (sessionAgentId !== agentIdOverride) {
      throw new Error(
        `Agent id "${agentIdOverrideRaw}" does not match session key agent "${sessionAgentId}".`,
      );
    }
  }
  if (agentIdOverride || explicitSessionKey) {
    if (!hasAgentDatabaseAdmissions()) {
      recordAgentDatabaseAdmissions(await evaluateAgentDatabaseAdmissions(cfg));
    }
    assertAgentDatabaseAdmitted(
      agentIdOverride ?? resolveSessionAgentId({ sessionKey: explicitSessionKey, config: cfg }),
    );
  }
  const agentCfg = cfg.agents?.defaults;

  const verboseOverride = normalizeVerboseLevel(opts.verbose);
  if (opts.verbose && !verboseOverride) {
    throw new Error('Invalid verbose level. Use "on", "full", or "off".');
  }

  const laneRaw = normalizeOptionalString(opts.lane) ?? "";
  const subagentLane: string = AGENT_LANE_SUBAGENT;
  const isSubagentLane = laneRaw === subagentLane;
  const hasExplicitTimeoutOption = opts.timeout !== undefined;
  const timeoutSecondsRaw = hasExplicitTimeoutOption
    ? (parseStrictNonNegativeInteger(opts.timeout) ?? Number.NaN)
    : isSubagentLane
      ? 0
      : undefined;
  if (
    timeoutSecondsRaw !== undefined &&
    (Number.isNaN(timeoutSecondsRaw) || timeoutSecondsRaw < 0)
  ) {
    throw new Error("--timeout must be a non-negative integer (seconds; 0 means no timeout)");
  }
  const timeoutMs = resolveAgentTimeoutMs({ cfg, overrideSeconds: timeoutSecondsRaw });
  const runTimeoutOverrideMs = hasExplicitTimeoutOption ? timeoutMs : undefined;

  const selectedCommandOpts = toSessionKey
    ? { ...opts, to: undefined, sessionKey: explicitSessionKey }
    : opts;
  const explicitRecipientSession =
    shouldResolveExplicitRecipientSession && agentIdOverride && recipientChannel && rawTo
      ? await resolveAgentExplicitRecipientSession({
          cfg,
          agentId: agentIdOverride,
          channel: recipientChannel,
          to: rawTo,
          accountId: selectedCommandOpts.accountId,
          threadId: selectedCommandOpts.threadId,
        })
      : undefined;
  if (explicitRecipientSession?.error) {
    throw explicitRecipientSession.error;
  }
  let commandOpts: AgentCommandOpts = explicitRecipientSession?.sessionKey
    ? {
        ...selectedCommandOpts,
        channel: explicitRecipientSession.channel,
        to: explicitRecipientSession.to,
        accountId: explicitRecipientSession.accountId,
        threadId: explicitRecipientSession.threadId,
      }
    : selectedCommandOpts;
  const sessionResolution = resolveSession({
    cfg,
    to: commandOpts.to,
    sessionId: commandOpts.sessionId,
    sessionKey: explicitSessionKey ?? explicitRecipientSession?.sessionKey,
    agentId: agentIdOverride,
  });
  const {
    sessionId,
    sessionKey,
    sessionEntry: sessionEntryRaw,
    storePath,
    isNewSession,
    previousSessionId,
    persistedThinking,
    persistedVerbose,
  } = sessionResolution;
  const harnessSessionError = sessionKey
    ? resolveAgentHarnessSessionContextError(sessionKey, sessionEntryRaw)
    : undefined;
  if (harnessSessionError) {
    throw new Error(harnessSessionError);
  }
  const isOneShotModelRun = opts.modelRun === true || opts.promptMode === "none";
  if (isOneShotModelRun && sessionKey && sessionEntryRaw?.modelSelectionLocked === true) {
    throw new Error(AGENT_HARNESS_MODEL_RUN_FORBIDDEN_MESSAGE);
  }
  const sessionStore: Record<string, InternalSessionEntry> =
    sessionKey && sessionEntryRaw ? { [sessionKey]: sessionEntryRaw } : {};
  const sessionAgentId =
    agentIdOverride ??
    resolveSessionAgentId({ sessionKey: sessionKey ?? explicitSessionKey, config: cfg });
  assertAgentDatabaseAdmitted(sessionAgentId);
  const outboundSession = buildOutboundSessionContext({
    cfg,
    agentId: sessionAgentId,
    sessionKey,
  });
  const workspaceDirRaw =
    normalizedSpawned.workspaceDir ?? resolveAgentWorkspaceDir(cfg, sessionAgentId);
  const workspaceDir = resolveUserPath(workspaceDirRaw);
  const { getAcpSessionManager } = await loadAcpManagerRuntime();
  const acpManager = getAcpSessionManager();
  const acpResolution = sessionKey
    ? acpManager.resolveSession({ cfg, sessionKey, agentId: sessionAgentId })
    : null;
  // Configured run cwd is a Gateway-local path; ACP-placed sessions ("ready" or
  // "stale") execute on their own node with a node-owned execCwd, so the config
  // fallback applies only to ordinary sessions and never bridges into a node.
  const isAcpPlacedSession = acpResolution !== null && acpResolution.kind !== "none";
  const cwd =
    normalizeOptionalString(opts.cwd) ??
    normalizeOptionalString(sessionEntryRaw?.spawnedCwd) ??
    (isAcpPlacedSession ? undefined : resolveAgentRunCwd(cfg, sessionAgentId));
  const agentDir = resolveAgentDir(cfg, sessionAgentId);
  const pluginsEnabled = cfg.plugins?.enabled !== false;
  const preparedMetadataSnapshot = runtimeContext?.pluginGeneration.pluginMetadataSnapshot;
  const manifestMetadataSnapshot = pluginsEnabled
    ? (preparedMetadataSnapshot ??
      resolvePluginMetadataSnapshot({ config: cfg, env: process.env, workspaceDir }))
    : undefined;
  const modelManifestContext = {
    manifestPlugins: manifestMetadataSnapshot ?? [],
  } satisfies ModelManifestNormalizationContext;
  const configuredModel = resolveConfiguredModelRef({
    cfg,
    agentId: sessionAgentId,
    defaultProvider: DEFAULT_PROVIDER,
    defaultModel: DEFAULT_MODEL,
    allowPluginNormalization: pluginsEnabled,
    ...modelManifestContext,
  });
  const configuredThinkingCatalog = buildConfiguredModelCatalog({
    cfg,
    workspaceDir,
    ...modelManifestContext,
  });
  const configuredThinkingRuntime = resolveEffectiveAgentRuntime({
    cfg,
    provider: configuredModel.provider,
    modelId: configuredModel.model,
    agentId: sessionAgentId,
    sessionKey,
    sessionEntry: sessionEntryRaw,
  });
  if (
    sessionEntryRaw &&
    commandOpts.cliSessionBindingFacts === undefined &&
    isSyntheticSourceReplyTurn({
      inputProvenance: commandOpts.inputProvenance,
      isHeartbeat: commandOpts.bootstrapContextRunKind === "heartbeat",
    })
  ) {
    commandOpts = {
      ...commandOpts,
      cliSessionBindingFacts: {
        sourceReplyDeliveryMode: resolveSessionStableReplyMode({
          cfg,
          ctx: { CommandAuthorized: false },
          sessionEntry: sessionEntryRaw,
          sessionAgentId,
          sessionKey,
        }),
      },
    };
  }
  const thinkingLevelsHint = formatThinkingLevels(
    configuredModel.provider,
    configuredModel.model,
    ", ",
    configuredThinkingCatalog.length > 0 ? configuredThinkingCatalog : undefined,
    configuredThinkingRuntime,
  );
  const thinkOverride = normalizeThinkLevel(opts.thinking);
  const thinkOnce = normalizeThinkLevel(opts.thinkingOnce);
  if (opts.thinking && !thinkOverride) {
    throw new Error(`Invalid thinking level. Use one of: ${thinkingLevelsHint}.`);
  }
  if (opts.thinkingOnce && !thinkOnce) {
    throw new Error(`Invalid one-shot thinking level. Use one of: ${thinkingLevelsHint}.`);
  }
  const resolvedCwd = cwd ? resolveUserPath(cwd) : undefined;
  const worktreeId = await resolveWorktreeIdForPath({
    sessionEntry: sessionEntryRaw,
    candidatePaths: [resolvedCwd ?? workspaceDir, workspaceDir],
  });
  const runLease = worktreeId ? await acquireWorktreeRunLease(worktreeId) : undefined;
  try {
    const { resolveAcpAgentWorkspaceProvisioningForTurn } =
      await import("../acp-workspace-provisioning.js");
    const workspaceProvisioning = await resolveAcpAgentWorkspaceProvisioningForTurn({
      cfg,
      agentId: sessionAgentId,
      workspaceDir,
      cwd: resolvedCwd,
      sessionKey: sessionKey ?? undefined,
      sessionEntry: sessionEntryRaw ?? undefined,
    });
    await ensureAgentWorkspace({
      dir: workspaceDirRaw,
      ensureBootstrapFiles: !agentCfg?.skipBootstrap,
      skipOptionalBootstrapFiles: agentCfg?.skipOptionalBootstrapFiles,
      provisioning: workspaceProvisioning,
    });
    const runId = opts.runId?.trim() || sessionId;
    let promptMessage = message;
    if (!isRawModelRun && (message.includes("$") || message.trimStart().startsWith("/"))) {
      const {
        expandExplicitSkillReferences,
        hasSkillReferenceCandidate,
        listSkillCommandsForWorkspace,
        resolveEffectiveAgentSkillFilter,
      } = await import("../../skills/discovery/chat-commands.runtime.js");
      const hasExplicitSkillCandidate =
        message.trimStart().startsWith("/") || hasSkillReferenceCandidate(message);
      if (hasExplicitSkillCandidate) {
        const skillFilter = resolveEffectiveAgentSkillFilter(cfg, sessionAgentId);
        const commandParams = {
          workspaceDir,
          cfg,
          agentId: sessionAgentId,
          sessionEntry: sessionEntryRaw,
          sessionKey,
          ...(preparedMetadataSnapshot ? { pluginMetadataSnapshot: preparedMetadataSnapshot } : {}),
          ...(skillFilter ? { skillFilter } : {}),
        };
        const skillCommands = listSkillCommandsForWorkspace(commandParams);
        const allSkillCommands = skillFilter
          ? listSkillCommandsForWorkspace({ ...commandParams, includeAllowlistHidden: true })
          : skillCommands;
        const expansion = expandExplicitSkillReferences({
          text: message,
          skillCommands,
          allSkillCommands,
        });
        if (expansion.error) {
          throw new Error(expansion.error);
        }
        promptMessage = expansion.body;
      }
    }
    const body =
      !isRawModelRun && acpResolution?.kind === "ready"
        ? resolveAcpPromptBody(promptMessage, opts.internalEvents, opts.inputProvenance)
        : prependInternalEventContext(promptMessage, opts.internalEvents, opts.inputProvenance);
    const transcriptBody =
      opts.transcriptMessage ??
      resolveInternalEventTranscriptBody(message, opts.internalEvents, opts.inputProvenance);

    const prepared = {
      opts: commandOpts,
      body,
      transcriptBody,
      cfg,
      configuredThinkingCatalog,
      normalizedSpawned,
      agentCfg,
      thinkOverride,
      thinkOnce,
      verboseOverride,
      timeoutMs,
      runTimeoutOverrideMs,
      sessionId,
      sessionKey,
      sessionEntry: sessionEntryRaw,
      sessionStore,
      storePath,
      isNewSession,
      previousSessionId,
      persistedThinking,
      persistedVerbose,
      sessionAgentId,
      outboundSession,
      workspaceDir,
      cwd: resolvedCwd,
      agentDir,
      pluginsEnabled,
      manifestMetadataSnapshot,
      ...(runtimeContext ? { commandRuntimeContext: runtimeContext } : {}),
      modelManifestContext,
      runId,
      isSubagentLane,
      acpManager,
      acpResolution,
      runLease,
    };
    return prepared;
  } catch (error) {
    await runLease?.release();
    throw error;
  }
}

export type PreparedAgentCommandExecution = Awaited<
  ReturnType<typeof prepareAgentCommandExecution>
>;