File size: 12,428 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
/** Mirrors child ACP turns into detached-task status for requester-facing progress. */
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
import type { AdmittedRunContext } from "../../agents/admitted-run-context.js";
import { isRetainedExecutionOwnerBinding } from "../../audit/execution-owner-binding.js";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { logVerbose } from "../../globals.js";
import { recordSubagentTerminalState } from "../../sessions/session-state-events.js";
import {
  createRunningTaskRun,
  completeTaskRunByRunId,
  failTaskRunByRunId,
  startTaskRunByRunId,
} from "../../tasks/detached-task-runtime.js";
import {
  createNextAcpTaskBackingDetail,
  readTaskBackingInstance,
} from "../../tasks/task-backing-authority.js";
import { resolveRequiredCompletionTerminalResult } from "../../tasks/task-completion-contract.js";
import { bindTaskFlowExecution } from "../../tasks/task-flow-registry.store.sqlite.js";
import { listTasksForRelatedSessionKey } from "../../tasks/task-registry-query.js";
import { bindTaskRunExecution } from "../../tasks/task-registry.store.sqlite.js";
import {
  deliveryContextFromSession,
  type DeliveryContext,
} from "../../utils/delivery-context.shared.js";
import { AcpRuntimeError } from "../runtime/errors.js";
import { ACP_TURN_TIMEOUT_DETAIL_CODE } from "./manager.turn-timeout.js";
import type { AcpRunTurnInput, AcpSessionManagerDeps } from "./manager.types.js";
import { resolveAcpSessionTarget } from "./manager.utils.js";
import { normalizeText } from "./runtime-options.js";

const ACP_BACKGROUND_TASK_TEXT_MAX_LENGTH = 160;
const ACP_BACKGROUND_TASK_PROGRESS_MAX_LENGTH = 240;

/** Context needed to mirror a child ACP turn into the requester task registry. */
type BackgroundTaskContext = {
  agentId: string;
  requesterAgentId: string;
  requesterSessionKey: string;
  requesterOrigin?: DeliveryContext;
  childSessionKey: string;
  runId: string;
  label?: string;
  task: string;
};

type BackgroundTaskRecord = {
  taskId: string;
  parentFlowId?: string;
};

/** Produces the bounded task label shown for a child ACP background run. */
function summarizeBackgroundTaskText(text: string): string {
  const normalized = normalizeText(text) ?? "ACP background task";
  if (normalized.length <= ACP_BACKGROUND_TASK_TEXT_MAX_LENGTH) {
    return normalized;
  }
  return `${truncateUtf16Safe(normalized, ACP_BACKGROUND_TASK_TEXT_MAX_LENGTH - 1)}…`;
}

/** Appends bounded progress text while preserving a single-line task summary. */
export function appendBackgroundTaskProgressSummary(current: string, chunk: string): string {
  const normalizedChunk = chunk.replace(/\s+/g, " ");
  if (!normalizedChunk) {
    return current;
  }
  const chunkToAppend = current ? normalizedChunk : normalizedChunk.trimStart();
  if (!chunkToAppend) {
    return current;
  }
  const combined = `${current}${chunkToAppend}`.replace(/\s+/g, " ");
  if (combined.length <= ACP_BACKGROUND_TASK_PROGRESS_MAX_LENGTH) {
    return combined;
  }
  return `${truncateUtf16Safe(combined, ACP_BACKGROUND_TASK_PROGRESS_MAX_LENGTH - 1)}…`;
}

/** Maps ACP runtime failures to detached-task terminal states. */
export function resolveBackgroundTaskFailureStatus(error: AcpRuntimeError): "failed" | "timed_out" {
  return error.detailCode === ACP_TURN_TIMEOUT_DETAIL_CODE ? "timed_out" : "failed";
}

/** Infers blocked terminal outcomes from final completion text when the child turn reports one. */
export function resolveBackgroundTaskTerminalResult(completionText: string): {
  terminalOutcome?: "blocked";
  terminalSummary?: string;
} {
  const requiredCompletionResult = resolveRequiredCompletionTerminalResult(completionText);
  if (requiredCompletionResult.terminalOutcome) {
    return requiredCompletionResult;
  }
  const normalized = normalizeText(completionText)?.replace(/\s+/g, " ").trim();
  if (!normalized) {
    return {};
  }
  const permissionDeniedMatch = normalized.match(
    /\b(?:write failed:\s*)?permission denied(?: for (?<path>\S+))?\.?/i,
  );
  if (permissionDeniedMatch) {
    const path = normalizeText(permissionDeniedMatch.groups?.path)?.replace(/[.,;:!?]+$/, "");
    return {
      terminalOutcome: "blocked",
      terminalSummary: path ? `Permission denied for ${path}.` : "Permission denied.",
    };
  }
  if (
    /\bneed a writable session\b/i.test(normalized) ||
    /\bfilesystem authorization\b/i.test(normalized) ||
    /`?apply_patch`?/i.test(normalized)
  ) {
    return {
      terminalOutcome: "blocked",
      terminalSummary: "Writable session or apply_patch authorization required.",
    };
  }
  return {};
}

/** Resolves the requester task context for a spawned child ACP session. */
export function resolveBackgroundTaskContext(params: {
  deps: AcpSessionManagerDeps;
  cfg: OpenClawConfig;
  sessionKey: string;
  agentId: string;
  requestId: string;
  text: string;
}): BackgroundTaskContext | null {
  const childEntry = params.deps.loadSessionEntry({
    cfg: params.cfg,
    sessionKey: params.sessionKey,
    agentId: params.agentId,
  })?.entry;
  const requesterSessionKey =
    normalizeText(childEntry?.spawnedBy) ?? normalizeText(childEntry?.parentSessionKey);
  if (!requesterSessionKey) {
    return null;
  }
  const requesterOwners = new Set(
    listTasksForRelatedSessionKey(params.sessionKey)
      .filter(
        (task) =>
          task.runtime === "acp" &&
          task.childSessionKey === params.sessionKey &&
          task.agentId === params.agentId &&
          (task.requesterSessionKey === requesterSessionKey ||
            task.ownerKey === requesterSessionKey),
      )
      .flatMap((task) => (task.requesterAgentId ? [task.requesterAgentId] : [])),
  );
  // Spawn stamps the requesting agent at creation, before the first dispatched
  // turn can reach task registration. This selects parent context, not authority.
  if (
    childEntry?.createdVia === "spawn" &&
    childEntry.createdActor?.type === "agent" &&
    childEntry.createdActor.id
  ) {
    requesterOwners.add(childEntry.createdActor.id);
  }
  if (requesterOwners.size > 1) {
    throw new AcpRuntimeError(
      "ACP_SESSION_INIT_FAILED",
      "ACP requester ownership is ambiguous; repair the child task relationship before retrying.",
    );
  }
  const parentTarget = resolveAcpSessionTarget({
    cfg: params.cfg,
    sessionKey: requesterSessionKey,
    agentId: requesterOwners.values().next().value,
  });
  const parentEntry = params.deps.loadSessionEntry({ cfg: params.cfg, ...parentTarget })?.entry;
  return {
    agentId: params.agentId,
    requesterAgentId: parentTarget.agentId,
    requesterSessionKey,
    requesterOrigin:
      deliveryContextFromSession(parentEntry) ?? deliveryContextFromSession(childEntry),
    childSessionKey: params.sessionKey,
    runId: params.requestId,
    label: normalizeText(childEntry?.label),
    task: summarizeBackgroundTaskText(params.text),
  };
}

export function createBackgroundTaskRecord(
  context: BackgroundTaskContext,
  startedAt: number,
  instanceId: string,
): BackgroundTaskRecord | undefined {
  try {
    const task = createRunningTaskRun({
      runtime: "acp",
      sourceId: context.runId,
      ownerKey: context.requesterSessionKey,
      agentId: context.agentId,
      requesterAgentId: context.requesterAgentId,
      scopeKind: "session",
      requesterOrigin: context.requesterOrigin,
      childSessionKey: context.childSessionKey,
      runId: context.runId,
      label: context.label,
      task: context.task,
      startedAt,
      detail: createNextAcpTaskBackingDetail({
        childSessionKey: context.childSessionKey,
        instanceId,
      }),
    });
    if (!task) {
      logVerbose(
        `acp-manager: failed creating background task for ${context.runId}: persist_failed`,
      );
      return undefined;
    }
    return {
      taskId: task.taskId,
      ...(task.parentFlowId ? { parentFlowId: task.parentFlowId } : {}),
    };
  } catch (error) {
    logVerbose(
      `acp-manager: failed creating background task for ${context.runId}: ${String(error)}`,
    );
    return undefined;
  }
}

/** Mirrors a cancelled actor wait without replacing a same-id predecessor's task. */
export function recordQueuedBackgroundTaskCancellation(params: {
  input: AcpRunTurnInput;
  deps: AcpSessionManagerDeps;
  sessionKey: string;
  agentId: string;
  startedAt: number;
}): void {
  if (params.input.mode !== "prompt") {
    return;
  }
  const { input, sessionKey, agentId } = params;
  const instanceId = input.admittedRunContext.operationalRunInstance.instanceId;
  const existing = listTasksForRelatedSessionKey(sessionKey, agentId).filter(
    (task) =>
      task.runtime === "acp" &&
      task.childSessionKey === sessionKey &&
      task.runId === input.requestId,
  );
  // Actor-wait cancellation bypasses serialization. It must not overwrite task
  // custody retained by an earlier operational instance with the same request id.
  if (
    existing.some((task) => {
      const backing = readTaskBackingInstance(task.detail);
      return backing?.runtime !== "acp" || backing.instanceId !== instanceId;
    })
  ) {
    return;
  }
  const context = resolveBackgroundTaskContext({
    ...params,
    cfg: input.cfg,
    requestId: input.requestId,
    text: input.text,
  });
  if (
    !context ||
    (existing.length === 0 && !createBackgroundTaskRecord(context, params.startedAt, instanceId))
  ) {
    return;
  }
  markBackgroundTaskTerminal(context.runId, {
    sessionKey,
    status: "cancelled",
    endedAt: Date.now(),
    lastEventAt: Date.now(),
    progressSummary: null,
    terminalSummary: null,
  });
  recordSubagentTerminalState({
    childSessionKey: sessionKey,
    runId: context.runId,
    requesterSessionKey: context.requesterSessionKey,
    outcomeStatus: "cancelled",
  });
}

/** Links ACP owner rows only when the runtime reaches its prompt-submitted boundary. */
export function bindBackgroundTaskExecution(
  record: BackgroundTaskRecord,
  admitted: AdmittedRunContext,
): void {
  try {
    const taskResult = bindTaskRunExecution({ admitted, taskId: record.taskId });
    const flowResult = record.parentFlowId
      ? isRetainedExecutionOwnerBinding(taskResult)
        ? bindTaskFlowExecution({ admitted, flowId: record.parentFlowId })
        : taskResult
      : undefined;
    if ([taskResult, flowResult].some((result) => result === "mismatch" || result === "missing")) {
      logVerbose("acp-manager: exact task execution binding was not retained");
    }
  } catch (error) {
    logVerbose(`acp-manager: failed binding background task execution: ${String(error)}`);
  }
}

export function markBackgroundTaskRunning(
  runId: string,
  params: {
    sessionKey?: string;
    lastEventAt?: number;
    progressSummary?: string | null;
  },
): void {
  try {
    startTaskRunByRunId({
      runId,
      runtime: "acp",
      sessionKey: params.sessionKey,
      lastEventAt: params.lastEventAt,
      progressSummary: params.progressSummary,
    });
  } catch (error) {
    logVerbose(`acp-manager: failed updating background task for ${runId}: ${String(error)}`);
  }
}

export function markBackgroundTaskTerminal(
  runId: string,
  params: {
    sessionKey?: string;
    status: "succeeded" | "failed" | "timed_out" | "cancelled";
    endedAt: number;
    lastEventAt?: number;
    error?: string;
    progressSummary?: string | null;
    terminalSummary?: string | null;
    terminalOutcome?: "succeeded" | "blocked" | null;
  },
): void {
  try {
    if (params.status === "succeeded") {
      completeTaskRunByRunId({
        runId,
        runtime: "acp",
        sessionKey: params.sessionKey,
        endedAt: params.endedAt,
        lastEventAt: params.lastEventAt,
        progressSummary: params.progressSummary,
        terminalSummary: params.terminalSummary,
        terminalOutcome: params.terminalOutcome,
      });
      return;
    }
    failTaskRunByRunId({
      runId,
      runtime: "acp",
      sessionKey: params.sessionKey,
      status: params.status,
      endedAt: params.endedAt,
      lastEventAt: params.lastEventAt,
      error: params.error,
      progressSummary: params.progressSummary,
      terminalSummary: params.terminalSummary,
    });
  } catch (error) {
    logVerbose(`acp-manager: failed updating background task for ${runId}: ${String(error)}`);
  }
}