@capybara-hq/kernel 0.1.0-rc.89 → 0.1.0-rc.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/background/poll.job.d.ts +10 -0
  2. package/dist/background/poll.job.js +41 -10
  3. package/dist/background/stop.d.ts +39 -7
  4. package/dist/background/stop.js +107 -19
  5. package/dist/background/store.d.ts +25 -3
  6. package/dist/background/store.js +32 -2
  7. package/dist/background/tasks.service.d.ts +16 -2
  8. package/dist/background/tasks.service.js +11 -2
  9. package/dist/catalog/marketplaces.service.d.ts +1 -1
  10. package/dist/config/schema.d.ts +1 -0
  11. package/dist/config/schema.js +11 -1
  12. package/dist/conversations/events.d.ts +5 -0
  13. package/dist/conversations/events.js +11 -0
  14. package/dist/db/kernel-schema.d.ts +4 -0
  15. package/dist/device-access/device-access.service.d.ts +4 -1
  16. package/dist/device-access/device-access.service.js +40 -11
  17. package/dist/device-access/viewer.js +3 -2
  18. package/dist/dial-in/gateway.d.ts +7 -0
  19. package/dist/dial-in/gateway.js +43 -4
  20. package/dist/dial-in/relay.d.ts +27 -5
  21. package/dist/dial-in/relay.js +83 -21
  22. package/dist/dial-in/streams.d.ts +13 -5
  23. package/dist/dial-in/streams.js +43 -30
  24. package/dist/overrides.d.ts +4 -0
  25. package/dist/overrides.js +2 -0
  26. package/dist/platform/ops/background.ops.js +5 -2
  27. package/dist/sandbox/device-services.d.ts +4 -2
  28. package/dist/sandbox/device-services.js +9 -7
  29. package/dist/sandbox/review/review.service.d.ts +5 -0
  30. package/dist/sandbox/review/review.service.js +1 -0
  31. package/dist/sandbox/review/rules.js +24 -0
  32. package/dist/sandbox/review/types.d.ts +6 -0
  33. package/dist/sandbox/sandbox.service.d.ts +23 -0
  34. package/dist/sandbox/sandbox.service.js +57 -9
  35. package/dist/tools/builtins/sandbox/common.js +6 -1
  36. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -1
  37. package/dist/tools/builtins/sandbox/task-stop.js +21 -3
  38. package/dist/tools/call-scope.d.ts +21 -0
  39. package/dist/tools/call-scope.js +25 -0
  40. package/dist/tools/pipeline.d.ts +20 -0
  41. package/dist/tools/pipeline.js +67 -5
  42. package/dist/tools/questions.service.d.ts +6 -0
  43. package/dist/tools/questions.service.js +1 -0
  44. package/dist/tools/registry.d.ts +15 -8
  45. package/dist/tools/registry.js +21 -10
  46. package/package.json +3 -3
  47. package/src/migrations/0184_background_cancel_failure.sql +10 -0
@@ -66,6 +66,16 @@ export declare class BackgroundTaskPollJob {
66
66
  * malformed ref is never used; an unavailable provider leaves its tasks as they are.
67
67
  */
68
68
  private pollManaged;
69
+ /**
70
+ * The owed exact stops of one tick; returns how many tasks finished. Bounded per tick: at most
71
+ * {@link MANAGED_STOPS_PER_TICK} stops that reach a provider, least recently attempted first (an
72
+ * attempt moves a task to the back, so one that keeps failing never holds the head); a task whose
73
+ * provider is not loaded takes no turn, and the rest stay owed for the next ticks. Each device's
74
+ * stops run one after another and the devices side by side, so one silent machine costs the tick
75
+ * at most one attempt's limit and never delays another device's stops; a device that did not
76
+ * answer (`unreachable`) gets no further attempt this tick.
77
+ */
78
+ private applyOwedStops;
69
79
  /** The exact statuses of one instance's acknowledged managed tasks; returns how many finished. */
70
80
  private pollManagedInstance;
71
81
  /**
@@ -176,30 +176,61 @@ let BackgroundTaskPollJob = class BackgroundTaskPollJob {
176
176
  });
177
177
  }
178
178
  }
179
- // Bounded per tick: at most this many stops that reach a provider, least recently attempted
180
- // first (an attempt moves a task to the back, so one that keeps failing never holds the head);
181
- // a task whose provider is not loaded takes no turn. The rest stay owed for the next ticks.
182
- let attempts = 0;
179
+ return n + (await this.applyOwedStops(cancels, signal));
180
+ }
181
+ /**
182
+ * The owed exact stops of one tick; returns how many tasks finished. Bounded per tick: at most
183
+ * {@link MANAGED_STOPS_PER_TICK} stops that reach a provider, least recently attempted first (an
184
+ * attempt moves a task to the back, so one that keeps failing never holds the head); a task whose
185
+ * provider is not loaded takes no turn, and the rest stay owed for the next ticks. Each device's
186
+ * stops run one after another and the devices side by side, so one silent machine costs the tick
187
+ * at most one attempt's limit and never delays another device's stops; a device that did not
188
+ * answer (`unreachable`) gets no further attempt this tick.
189
+ */
190
+ async applyOwedStops(cancels, signal) {
191
+ const byDevice = new Map();
192
+ let turns = 0;
183
193
  for (const t of cancels) {
184
- if (signal.aborted || attempts >= MANAGED_STOPS_PER_TICK)
194
+ if (turns >= MANAGED_STOPS_PER_TICK)
185
195
  break;
186
196
  try {
187
197
  // revocation delivery needs the provider loaded only (not on in the org)
188
198
  if (!(await this.sandbox.providerLoaded(t.deviceId)))
189
199
  continue;
190
- attempts++;
191
- const after = await this.stopper.stop(t, "revoked", signal);
192
- if (after.status !== "running")
193
- n++;
194
200
  }
195
201
  catch (err) {
196
202
  this.log.warn("cannot apply an owed background task cancellation; retrying next tick", {
197
203
  taskId: t.id,
198
204
  err,
199
205
  });
206
+ continue;
200
207
  }
208
+ turns++;
209
+ const key = t.deviceId;
210
+ byDevice.set(key, [...(byDevice.get(key) ?? []), t]);
201
211
  }
202
- return n;
212
+ const finished = await Promise.all([...byDevice.values()].map(async (tasks) => {
213
+ let n = 0;
214
+ for (const t of tasks) {
215
+ if (signal.aborted)
216
+ break;
217
+ try {
218
+ const after = await this.stopper.stop(t, "revoked", signal);
219
+ if (after.status !== "running")
220
+ n++;
221
+ else if (after.cancelFailure === "unreachable")
222
+ break;
223
+ }
224
+ catch (err) {
225
+ this.log.warn("cannot apply an owed background task cancellation; retrying next tick", {
226
+ taskId: t.id,
227
+ err,
228
+ });
229
+ }
230
+ }
231
+ return n;
232
+ }));
233
+ return finished.reduce((a, b) => a + b, 0);
203
234
  }
204
235
  /** The exact statuses of one instance's acknowledged managed tasks; returns how many finished. */
205
236
  async pollManagedInstance(tasks, signal) {
@@ -2,7 +2,34 @@ import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import type { KernelLogger } from "../log.js";
3
3
  import { SandboxService } from "../sandbox/sandbox.service.js";
4
4
  import { type BackgroundFinish, BackgroundTaskFinisher } from "./finish.js";
5
- import { type BackgroundTaskRow, BackgroundTaskStore } from "./store.js";
5
+ import { type BackgroundTaskRow, BackgroundTaskStore, type CancelFailure } from "./store.js";
6
+ /**
7
+ * The most one exact stop attempt of a managed task may take: the wait for the instance's lease,
8
+ * the device's stop with its five-second grace, and the tail. A device that has not answered by
9
+ * then (its machine offline or silent, a busy lease) does not hold the person, the tool or the
10
+ * poll: the stop stays owed (`cancel-pending`) and the poller attempts it again.
11
+ */
12
+ export declare const STOP_ATTEMPT_TIMEOUT_MS = 20000;
13
+ /**
14
+ * Whether `err` (or an error in its `cause` chain: an unknown outcome wraps the transport's error)
15
+ * says the device's machine did not take or answer the request: not connected, gone away or
16
+ * reconnected mid-request, its program restarted, silent past the deadline, or the request never
17
+ * sent. Recognized by the SDK's recognizers (by name and tag, so a provider's own SDK copy
18
+ * matches), never by `instanceof`.
19
+ */
20
+ export declare function isUnreachable(err: unknown): boolean;
21
+ /**
22
+ * Why one stop attempt did not settle, or undefined when the caller gave up (that says nothing
23
+ * about the device, so the last attempt's failure is kept).
24
+ */
25
+ export declare function attemptFailure(err: unknown, attemptTimedOut: boolean, callerAborted: boolean): {
26
+ kind: CancelFailure;
27
+ detail: string;
28
+ } | undefined;
29
+ /**
30
+ * Test seam (`KernelOverride`): a shorter {@link STOP_ATTEMPT_TIMEOUT_MS}, read at every attempt.
31
+ */
32
+ export declare const BACKGROUND_STOP_ATTEMPT_MS: unique symbol;
6
33
  /**
7
34
  * Why a task is stopped. `revoked`: the cancellation a revocation owes (its finish may wake the
8
35
  * conversation, unless a stop asked for it before: that asker's rule holds).
@@ -26,17 +53,22 @@ export declare class BackgroundTaskStopper {
26
53
  private readonly sandbox;
27
54
  private readonly db;
28
55
  private readonly log;
29
- constructor(store: Pick<BackgroundTaskStore, "get" | "runningOwnedBy" | "runningIn" | "claimStop" | "releaseStop" | "requestCancel" | "noteCancelAttempt">, finisher: BackgroundTaskFinisher, sandbox: Pick<SandboxService, "ifRunning">, db: KernelDb, log: Pick<KernelLogger, "warn">);
56
+ private readonly attemptMs;
57
+ constructor(store: Pick<BackgroundTaskStore, "get" | "runningOwnedBy" | "runningIn" | "claimStop" | "releaseStop" | "requestCancel" | "oweCancel" | "noteCancelAttempt">, finisher: BackgroundTaskFinisher, sandbox: Pick<SandboxService, "ifRunning">, db: KernelDb, log: Pick<KernelLogger, "warn">, attemptMs?: () => number);
30
58
  /**
31
59
  * Stops `task` and returns its row afterwards. A task that is no longer running, or that another
32
60
  * live stop already claimed, is returned as it is now.
33
61
  *
34
62
  * The stop first claims the task (`stopping_at`), so the poller leaves it alone while the stop
35
- * takes effect and the stop's finish is its only one. A legacy reservation that never started
36
- * (no instance) is only claimed: the poller fails it as abandoned. When the stop fails while the
37
- * sandbox runs (busy, a provider error, a legacy task's retirement refusal), the claim is given
38
- * up, the task stays `running` and the error is thrown. `how.reported`: the caller's own result
39
- * tells the model this finish (a managed task's cancellation settled from a TaskOutput read).
63
+ * takes effect and the stop's finish is its only one. A stop that loses the claim to another
64
+ * live stop still records its asker on a managed task, so the later finish keeps their wake
65
+ * rule. A legacy reservation that never started (no instance) is only claimed: the poller fails
66
+ * it as abandoned. A managed task's stop is owed before the device is asked and never throws for
67
+ * the device: one that cannot settle within its attempt stays owed (`cancel-pending`, why in
68
+ * `cancelFailure`) for the poller. A legacy task's retirement refusal, a malformed ref and a
69
+ * failed write give the claim up and throw, the task staying `running`. `how.reported`: the
70
+ * caller's own result tells the model this finish (a managed task's cancellation settled from a
71
+ * TaskOutput read).
40
72
  */
41
73
  stop(task: BackgroundTaskRow, why: StopReason, signal?: AbortSignal, how?: {
42
74
  reported?: boolean;
@@ -7,13 +7,65 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { Inject, Injectable } from "@nestjs/common";
10
+ import { isDeviceOfflineError, isDeviceRequestNotSent, isDialInAnswerTimeoutError, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable, Optional } from "@nestjs/common";
11
12
  import { KernelDb } from "../infra/database/kernel-db.js";
12
13
  import { KERNEL_LOGGER } from "../infra/tokens.js";
14
+ import { isDeviceProgramRestarted } from "../sandbox/request-not-sent.js";
13
15
  import { retirementPending, SandboxService, } from "../sandbox/sandbox.service.js";
14
16
  import { BackgroundTaskFinisher, } from "./finish.js";
15
17
  import { exactRefOf, lastLinesByRef, MANAGED_STOP_GRACE_MS, onManagedInstance, stopEnd, summaryLines, } from "./managed.js";
16
18
  import { BackgroundTaskStore, isManagedTask, } from "./store.js";
19
+ /**
20
+ * The most one exact stop attempt of a managed task may take: the wait for the instance's lease,
21
+ * the device's stop with its five-second grace, and the tail. A device that has not answered by
22
+ * then (its machine offline or silent, a busy lease) does not hold the person, the tool or the
23
+ * poll: the stop stays owed (`cancel-pending`) and the poller attempts it again.
24
+ */
25
+ export const STOP_ATTEMPT_TIMEOUT_MS = 20_000;
26
+ /** The longest failure message kept on the row for the model and the logs. */
27
+ const FAILURE_DETAIL_MAX = 300;
28
+ /**
29
+ * Whether `err` (or an error in its `cause` chain: an unknown outcome wraps the transport's error)
30
+ * says the device's machine did not take or answer the request: not connected, gone away or
31
+ * reconnected mid-request, its program restarted, silent past the deadline, or the request never
32
+ * sent. Recognized by the SDK's recognizers (by name and tag, so a provider's own SDK copy
33
+ * matches), never by `instanceof`.
34
+ */
35
+ export function isUnreachable(err) {
36
+ for (let e = err, depth = 0; e instanceof Error && depth < 5; depth++) {
37
+ if (isDeviceOfflineError(e) ||
38
+ isDialInAnswerTimeoutError(e) ||
39
+ isDeviceRequestNotSent(e) ||
40
+ isDeviceProgramRestarted(e) ||
41
+ e.name === "DialInConnectionChangedError")
42
+ return true;
43
+ e = e.cause;
44
+ }
45
+ return false;
46
+ }
47
+ /**
48
+ * Why one stop attempt did not settle, or undefined when the caller gave up (that says nothing
49
+ * about the device, so the last attempt's failure is kept).
50
+ */
51
+ export function attemptFailure(err, attemptTimedOut, callerAborted) {
52
+ if (callerAborted)
53
+ return undefined;
54
+ const message = err instanceof Error ? err.message : String(err);
55
+ const detail = message.length > FAILURE_DETAIL_MAX ? `${message.slice(0, FAILURE_DETAIL_MAX)}…` : message;
56
+ if (attemptTimedOut)
57
+ return {
58
+ kind: "unreachable",
59
+ detail: "the device did not answer within the stop attempt's time limit",
60
+ };
61
+ if (isUnreachable(err))
62
+ return { kind: "unreachable", detail };
63
+ return { kind: "failed", detail };
64
+ }
65
+ /**
66
+ * Test seam (`KernelOverride`): a shorter {@link STOP_ATTEMPT_TIMEOUT_MS}, read at every attempt.
67
+ */
68
+ export const BACKGROUND_STOP_ATTEMPT_MS = Symbol("BACKGROUND_STOP_ATTEMPT_MS");
17
69
  /** How a task whose sandbox is not running ends (`ifRunning`'s `not_running` status). */
18
70
  export function notRunningAs(status, killPending) {
19
71
  return {
@@ -53,27 +105,38 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
53
105
  sandbox;
54
106
  db;
55
107
  log;
56
- constructor(store, finisher, sandbox, db, log) {
108
+ attemptMs;
109
+ constructor(store, finisher, sandbox, db, log, attemptMs = () => STOP_ATTEMPT_TIMEOUT_MS) {
57
110
  this.store = store;
58
111
  this.finisher = finisher;
59
112
  this.sandbox = sandbox;
60
113
  this.db = db;
61
114
  this.log = log;
115
+ this.attemptMs = attemptMs;
62
116
  }
63
117
  /**
64
118
  * Stops `task` and returns its row afterwards. A task that is no longer running, or that another
65
119
  * live stop already claimed, is returned as it is now.
66
120
  *
67
121
  * The stop first claims the task (`stopping_at`), so the poller leaves it alone while the stop
68
- * takes effect and the stop's finish is its only one. A legacy reservation that never started
69
- * (no instance) is only claimed: the poller fails it as abandoned. When the stop fails while the
70
- * sandbox runs (busy, a provider error, a legacy task's retirement refusal), the claim is given
71
- * up, the task stays `running` and the error is thrown. `how.reported`: the caller's own result
72
- * tells the model this finish (a managed task's cancellation settled from a TaskOutput read).
122
+ * takes effect and the stop's finish is its only one. A stop that loses the claim to another
123
+ * live stop still records its asker on a managed task, so the later finish keeps their wake
124
+ * rule. A legacy reservation that never started (no instance) is only claimed: the poller fails
125
+ * it as abandoned. A managed task's stop is owed before the device is asked and never throws for
126
+ * the device: one that cannot settle within its attempt stays owed (`cancel-pending`, why in
127
+ * `cancelFailure`) for the poller. A legacy task's retirement refusal, a malformed ref and a
128
+ * failed write give the claim up and throw, the task staying `running`. `how.reported`: the
129
+ * caller's own result tells the model this finish (a managed task's cancellation settled from a
130
+ * TaskOutput read).
73
131
  */
74
132
  async stop(task, why, signal, how = {}) {
75
- if (!(await this.store.claimStop(task.id)))
133
+ if (!(await this.store.claimStop(task.id))) {
134
+ // another live stop holds the claim (a poller attempt, a second click): this asker's wake
135
+ // rule still holds for the finish whoever settles it
136
+ if (why !== "revoked" && isManagedTask(task))
137
+ await this.store.requestCancel(task.id, why, false);
76
138
  return (await this.store.get(task.id)) ?? task;
139
+ }
77
140
  // read after the claim: an acknowledgement recording the ref before the claim is seen here,
78
141
  // one recording it after sees the claim (both are single-row updates of the same row)
79
142
  const cur = (await this.store.get(task.id)) ?? task;
@@ -182,37 +245,60 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
182
245
  // `reportedHere`: the caller's own result tells the model this finish (a TaskOutput read)
183
246
  const reported = reportedHere ?? (by === "tool" && why === "tool");
184
247
  const opts = stoppedByOpts(by);
185
- const pending = async () => {
186
- await this.store.requestCancel(cur.id, asker, true);
248
+ const pending = async (failure) => {
249
+ await this.store.requestCancel(cur.id, asker, true, failure);
187
250
  return (await this.store.get(cur.id)) ?? cur;
188
251
  };
189
- let r;
190
252
  try {
191
253
  exactRefOf(cur);
254
+ // intent first: from here on the stop is owed whatever happens to this attempt (the device
255
+ // offline or silent, this replica gone); the claim keeps the poller away while it runs
256
+ await this.store.oweCancel(cur.id, asker);
257
+ }
258
+ catch (err) {
259
+ // a malformed ref is never used and owes nothing (the poller skips it too); a failed write
260
+ // recorded nothing: either way the claim is given up and the caller hears why
261
+ await this.store
262
+ .releaseStop(cur.id)
263
+ .catch((e) => this.log.warn("cannot release a background task stop", { taskId: cur.id, err: e }));
264
+ throw err;
265
+ }
266
+ const timeout = AbortSignal.timeout(this.attemptMs());
267
+ const attempt = AbortSignal.any([...(signal ? [signal] : []), timeout]);
268
+ let r;
269
+ try {
192
270
  await this.store.noteCancelAttempt(cur.id);
193
271
  r = await onManagedInstance(this.sandbox.ifRunning.bind(this.sandbox), cur, async (bg, h, ref, sig) => {
194
272
  const to = stopEnd(await bg.stop(h, ref, { graceMs: MANAGED_STOP_GRACE_MS, signal: sig }));
195
273
  // once the provider claimed the outcome it stands: a failed tail only loses the lines
196
274
  const lines = to === null ? "" : summaryLines(await lastLinesByRef(bg, h, ref, sig));
197
275
  return { to, lastLines: lines };
198
- }, signal);
276
+ }, attempt);
199
277
  }
200
278
  catch (err) {
201
- await this.store
202
- .releaseStop(cur.id)
203
- .catch((e) => this.log.warn("cannot release a background task stop", { taskId: cur.id, err: e }));
204
- throw err;
279
+ // the device could not take the stop now (its machine offline or silent past the attempt's
280
+ // limit, a provider error) or the caller gave up: the stop stays owed and the claim is
281
+ // released, so the poller attempts it again; the task's own time limit still ends it on
282
+ // the device
283
+ const failure = attemptFailure(err, timeout.aborted && !signal?.aborted, signal?.aborted === true);
284
+ this.log.warn("a background task stop did not settle; it stays owed", {
285
+ taskId: cur.id,
286
+ failure: failure?.kind ?? "caller_aborted",
287
+ err,
288
+ });
289
+ return pending(failure);
205
290
  }
206
291
  if (r.kind === "ran") {
292
+ // the device recorded the cancellation and applies it later: nothing failed
207
293
  if (r.value.to === null)
208
- return pending();
294
+ return pending(null);
209
295
  await this.finisher.finish(cur, r.value.to, r.value.lastLines, reported, opts);
210
296
  }
211
297
  else if (r.kind === "not_running") {
212
298
  // never resumed for a stop: a suspended instance keeps the cancellation owed; a missing or
213
299
  // destroyed one is lost like an acknowledged task's (the uncertain record is retained)
214
300
  if (r.status === "suspended")
215
- return pending();
301
+ return pending(null);
216
302
  await this.finisher.finish(cur, notRunningAs(r.status, false), "", reported, opts);
217
303
  }
218
304
  else {
@@ -300,6 +386,8 @@ BackgroundTaskStopper = __decorate([
300
386
  __param(1, Inject(BackgroundTaskFinisher)),
301
387
  __param(2, Inject(SandboxService)),
302
388
  __param(3, Inject(KernelDb)),
303
- __param(4, Inject(KERNEL_LOGGER))
389
+ __param(4, Inject(KERNEL_LOGGER)),
390
+ __param(5, Optional()),
391
+ __param(5, Inject(BACKGROUND_STOP_ATTEMPT_MS))
304
392
  ], BackgroundTaskStopper);
305
393
  export { BackgroundTaskStopper };
@@ -69,7 +69,17 @@ export interface BackgroundTaskRow {
69
69
  cancelRequestedAt: Date | null;
70
70
  /** Who asked for it by a stop (0153); null for a revocation's cancellation or none. */
71
71
  cancelRequestedBy: CancelRequester | null;
72
+ /**
73
+ * Why the owed stop did not settle at its last attempt (0184): `unreachable` (the device did not
74
+ * answer in time, or its machine is not connected), `failed` (the device or its provider failed
75
+ * the stop); null when no attempt failed.
76
+ */
77
+ cancelFailure: CancelFailure | null;
78
+ /** That failure's message, clipped; null without one. */
79
+ cancelFailureDetail: string | null;
72
80
  }
81
+ /** Why an owed stop did not settle at its last attempt. */
82
+ export type CancelFailure = "unreachable" | "failed";
73
83
  /** Who asked for a managed task's stop: their wake rule holds for its later finish. */
74
84
  export type CancelRequester = "tool" | "person" | "conversation_deleted" | "subagent_end";
75
85
  /** Whether `task` is a managed (exact-ref) task rather than a legacy SID one. */
@@ -106,7 +116,7 @@ export type ManagedReservation = {
106
116
  } | {
107
117
  kind: "full";
108
118
  };
109
- export type BackgroundTaskInsert = Omit<BackgroundTaskRow, "status" | "finishedAt" | "exitCode" | "lostReason" | "killPending" | "readOffset" | "stoppingAt" | "launchState" | "operationId" | "workingRoot" | "retainUntil" | "executionRef" | "instanceId" | "instanceGeneration" | "cancelRequestedAt" | "cancelRequestedBy">;
119
+ export type BackgroundTaskInsert = Omit<BackgroundTaskRow, "status" | "finishedAt" | "exitCode" | "lostReason" | "killPending" | "readOffset" | "stoppingAt" | "launchState" | "operationId" | "workingRoot" | "retainUntil" | "executionRef" | "instanceId" | "instanceGeneration" | "cancelRequestedAt" | "cancelRequestedBy" | "cancelFailure" | "cancelFailureDetail">;
110
120
  /**
111
121
  * How long a stop's claim holds: a claim older than this is abandoned (its stopper died), so the
112
122
  * poller checks the task again and another stop may claim it. Longer than any stop takes (the
@@ -203,13 +213,25 @@ export declare class BackgroundTaskStore {
203
213
  /** Records that an exact stop of the task is being attempted now (its owed-stop turn moves back). */
204
214
  noteCancelAttempt(id: string): Promise<void>;
205
215
  /**
206
- * Records who asked for a running managed task's stop (the first asker is kept) and when. With
216
+ * Records who asked for a running managed task's stop (the first asker is kept) and when, and
217
+ * with `failure` why its last attempt did not settle (null: it did not fail). With
207
218
  * `release` (the stop could not settle now: the provider recorded a pending cancellation, or the
208
219
  * instance is not reachable) an acknowledged task becomes `cancel-pending` and the stop's claim
209
220
  * is given up, so the poller owes the exact stop; without, the claim stays (a task without its
210
221
  * ref yet: the dispatch binding or the acknowledgement turns the claim into the owed cancel).
211
222
  */
212
- requestCancel(id: string, by: CancelRequester | null, release: boolean): Promise<void>;
223
+ requestCancel(id: string, by: CancelRequester | null, release: boolean, failure?: {
224
+ kind: CancelFailure;
225
+ detail: string;
226
+ } | null): Promise<void>;
227
+ /**
228
+ * Records a running acknowledged task's stop as owed before the device is asked (intent first):
229
+ * the asker is kept (the first one wins) and the task becomes `cancel-pending`, while the stop's
230
+ * claim (`stopping_at`) stays. A stop that settles finishes the task; one that cannot settle now
231
+ * releases the claim ({@link requestCancel}), and the poller delivers the owed stop. A stop
232
+ * whose replica died leaves the same record: the claim expires and the poller delivers it.
233
+ */
234
+ oweCancel(id: string, by: CancelRequester | null): Promise<void>;
213
235
  /** The running tasks one conversation owns (not those of its sub-agents), oldest first. */
214
236
  runningOwnedBy(conversationId: string): Promise<BackgroundTaskRow[]>;
215
237
  /**
@@ -50,6 +50,8 @@ const toRow = (r) => ({
50
50
  instanceGeneration: r.instance_generation,
51
51
  cancelRequestedAt: r.cancel_requested_at === null ? null : new Date(r.cancel_requested_at),
52
52
  cancelRequestedBy: r.cancel_requested_by,
53
+ cancelFailure: r.cancel_failure,
54
+ cancelFailureDetail: r.cancel_failure_detail,
53
55
  });
54
56
  /**
55
57
  * How long a stop's claim holds: a claim older than this is abandoned (its stopper died), so the
@@ -382,7 +384,8 @@ let BackgroundTaskStore = class BackgroundTaskStore {
382
384
  .execute();
383
385
  }
384
386
  /**
385
- * Records who asked for a running managed task's stop (the first asker is kept) and when. With
387
+ * Records who asked for a running managed task's stop (the first asker is kept) and when, and
388
+ * with `failure` why its last attempt did not settle (null: it did not fail). With
386
389
  * `release` (the stop could not settle now: the provider recorded a pending cancellation, or the
387
390
  * instance is not reachable) an acknowledged task becomes `cancel-pending` and the stop's claim
388
391
  * is given up, so the poller owes the exact stop; without, the claim stays (a task without its
@@ -390,12 +393,17 @@ let BackgroundTaskStore = class BackgroundTaskStore {
390
393
  */
391
394
  // org-filter: by task id: callers check ownership first (ownedTask: the calling conversation;
392
395
  // TasksService.owned: org and conversation scope) or pass the id of a row they already read
393
- async requestCancel(id, by, release) {
396
+ async requestCancel(id, by, release, failure) {
394
397
  await this.db
395
398
  .updateTable("background_tasks")
396
399
  .set({
397
400
  cancel_requested_by: sql `COALESCE(cancel_requested_by, ${by}::text)`,
398
401
  cancel_requested_at: sql `COALESCE(cancel_requested_at, now())`,
402
+ // undefined keeps the last attempt's failure (a caller that gave up learned nothing new)
403
+ ...(failure !== undefined && {
404
+ cancel_failure: failure?.kind ?? null,
405
+ cancel_failure_detail: failure?.detail ?? null,
406
+ }),
399
407
  ...(release && {
400
408
  stopping_at: null,
401
409
  launch_state: sql `CASE WHEN launch_state = 'acknowledged' THEN 'cancel-pending' ELSE launch_state END`,
@@ -406,6 +414,28 @@ let BackgroundTaskStore = class BackgroundTaskStore {
406
414
  .where("launch_state", "<>", "legacy")
407
415
  .execute();
408
416
  }
417
+ /**
418
+ * Records a running acknowledged task's stop as owed before the device is asked (intent first):
419
+ * the asker is kept (the first one wins) and the task becomes `cancel-pending`, while the stop's
420
+ * claim (`stopping_at`) stays. A stop that settles finishes the task; one that cannot settle now
421
+ * releases the claim ({@link requestCancel}), and the poller delivers the owed stop. A stop
422
+ * whose replica died leaves the same record: the claim expires and the poller delivers it.
423
+ */
424
+ // org-filter: by task id: callers check ownership first (ownedTask: the calling conversation;
425
+ // TasksService.owned: org and conversation scope) or pass the id of a row they already read
426
+ async oweCancel(id, by) {
427
+ await this.db
428
+ .updateTable("background_tasks")
429
+ .set({
430
+ cancel_requested_by: sql `COALESCE(cancel_requested_by, ${by}::text)`,
431
+ cancel_requested_at: sql `COALESCE(cancel_requested_at, now())`,
432
+ launch_state: sql `CASE WHEN launch_state = 'acknowledged' THEN 'cancel-pending' ELSE launch_state END`,
433
+ })
434
+ .where("id", "=", id)
435
+ .where("status", "=", "running")
436
+ .where("launch_state", "<>", "legacy")
437
+ .execute();
438
+ }
409
439
  /** The running tasks one conversation owns (not those of its sub-agents), oldest first. */
410
440
  // org-filter: by conversation id the caller already resolved in its org (the tool call's
411
441
  // conversation, TasksService.scope(orgId, ...), or a kernel launch / deletion path)
@@ -5,7 +5,7 @@ import { type PersonRef } from "../identity/account-avatar.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { SandboxService } from "../sandbox/sandbox.service.js";
7
7
  import { BackgroundTaskStopper } from "./stop.js";
8
- import { type BackgroundTaskStatus, BackgroundTaskStore } from "./store.js";
8
+ import { type BackgroundTaskStatus, BackgroundTaskStore, type CancelFailure } from "./store.js";
9
9
  /** The most bytes of output one read returns. */
10
10
  export declare const OUTPUT_TAIL_MAX_BYTES = 65536;
11
11
  /** A task as the API shows it. */
@@ -26,6 +26,19 @@ export interface BackgroundTaskView {
26
26
  finishedAt: string | null;
27
27
  /** True while a stop has claimed the task and it is still running. */
28
28
  stopping: boolean;
29
+ /**
30
+ * True while the task's stop is recorded and owed but no attempt is under way (with
31
+ * `stopping`): the device has not applied it yet; the poller attempts it again. `stopFailure`
32
+ * says why the last attempt did not settle.
33
+ */
34
+ stopWaiting: boolean;
35
+ /**
36
+ * Why the owed stop's last attempt did not settle: `unreachable` (the device did not answer in
37
+ * time, or its machine is not connected), `failed` (the device or its provider failed the stop);
38
+ * null when no attempt failed (the device recorded the cancellation and applies it later, or
39
+ * its instance is suspended).
40
+ */
41
+ stopFailure: CancelFailure | null;
29
42
  /**
30
43
  * True while the task's start was sent but not yet confirmed (a managed launch without its
31
44
  * exact ref, still `running`): the kernel is reconciling it under its original identity, and it
@@ -88,7 +101,8 @@ export declare class BackgroundTasks {
88
101
  /**
89
102
  * A person's stop. Returns the row after the stop: `running` with `stopping` true when another
90
103
  * stop already claimed the task (or the task is a reservation still launching, which its launch
91
- * then kills); a stop that fails throws. Writes the `background_task.stopped` audit event.
104
+ * then kills), or when the device has not applied it yet (`stopWaiting`, the stop owed and
105
+ * delivered by the poller); a legacy task's retirement refusal throws. Writes the `background_task.stopped` audit event.
92
106
  */
93
107
  stop(orgId: string, conversationId: string, accountId: string, taskId: string, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<BackgroundTaskView>;
94
108
  /**
@@ -26,7 +26,7 @@ import { TASK_ID_RE } from "./launch.js";
26
26
  import { ManagedInstanceMismatchError, ManagedRefError, onManagedInstance, readerOf, } from "./managed.js";
27
27
  import { assembleOutputSuffix, ManagedOutputCapacityError, ManagedOutputUnavailableError, } from "./managed-output.js";
28
28
  import { BackgroundTaskStopper } from "./stop.js";
29
- import { BackgroundTaskStore, isManagedTask, } from "./store.js";
29
+ import { BackgroundTaskStore, isManagedTask, STOP_CLAIM_TTL_MS, } from "./store.js";
30
30
  /** The most bytes of output one read returns. */
31
31
  export const OUTPUT_TAIL_MAX_BYTES = 65_536;
32
32
  /** The time limit of reading an output (the exact reads and the wait for the sandbox's lease). */
@@ -90,6 +90,14 @@ let BackgroundTasks = class BackgroundTasks {
90
90
  // a managed task's owed cancellation is a stop in progress too
91
91
  stopping: task.status === "running" &&
92
92
  (task.stoppingAt !== null || task.launchState === "cancel-pending"),
93
+ // owed and not being attempted right now (an attempt holds a live claim; an expired claim
94
+ // is a replica that died mid-attempt, the poller's again)
95
+ stopWaiting: task.status === "running" &&
96
+ task.launchState === "cancel-pending" &&
97
+ (task.stoppingAt === null || task.stoppingAt.getTime() < Date.now() - STOP_CLAIM_TTL_MS),
98
+ stopFailure: task.status === "running" && task.launchState === "cancel-pending"
99
+ ? task.cancelFailure
100
+ : null,
93
101
  starting: task.status === "running" &&
94
102
  task.executionRef === null &&
95
103
  (task.launchState === "pending" || task.launchState === "dispatched"),
@@ -112,7 +120,8 @@ let BackgroundTasks = class BackgroundTasks {
112
120
  /**
113
121
  * A person's stop. Returns the row after the stop: `running` with `stopping` true when another
114
122
  * stop already claimed the task (or the task is a reservation still launching, which its launch
115
- * then kills); a stop that fails throws. Writes the `background_task.stopped` audit event.
123
+ * then kills), or when the device has not applied it yet (`stopWaiting`, the stop owed and
124
+ * delivered by the poller); a legacy task's retirement refusal throws. Writes the `background_task.stopped` audit event.
116
125
  */
117
126
  async stop(orgId, conversationId, accountId, taskId, actorTokenId, auditDetail) {
118
127
  const task = await this.owned(orgId, conversationId, accountId, taskId);
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.71";
211
+ readonly sdk: "0.1.0-rc.72";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -160,6 +160,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
160
160
  }, z.core.$strict>>;
161
161
  tools: z.ZodDefault<z.ZodObject<{
162
162
  timeoutMs: z.ZodDefault<z.ZodNumber>;
163
+ maxTimeoutMs: z.ZodDefault<z.ZodNumber>;
163
164
  breakerFailures: z.ZodDefault<z.ZodNumber>;
164
165
  breakerOpenSeconds: z.ZodDefault<z.ZodNumber>;
165
166
  outputSpillChars: z.ZodDefault<z.ZodNumber>;
@@ -1,5 +1,5 @@
1
1
  import { isIP } from "node:net";
2
- import { CATALOG_ITEM_NAME_RE, DOCUMENT_MEDIA_TYPES, EXTENSION_NAME_RE, IMAGE_MEDIA_TYPES, validateAllowHost, } from "@capybara-hq/plugin-sdk";
2
+ import { CATALOG_ITEM_NAME_RE, DOCUMENT_MEDIA_TYPES, EXTENSION_NAME_RE, IMAGE_MEDIA_TYPES, TOOL_TIMEOUT_MAX_MS, validateAllowHost, } from "@capybara-hq/plugin-sdk";
3
3
  import { z } from "zod";
4
4
  import { LOG_FORMATS, LOG_LEVELS } from "../log.js";
5
5
  import { noProxyEntryProblem, proxyUrlProblem } from "../net/proxy.js";
@@ -888,6 +888,15 @@ export const KernelConfigSchema = z.strictObject({
888
888
  .positive()
889
889
  .default(60000)
890
890
  .meta(meta({ description: "Timeout of one tool call in milliseconds" })),
891
+ maxTimeoutMs: z
892
+ .number()
893
+ .int()
894
+ .positive()
895
+ .max(TOOL_TIMEOUT_MAX_MS)
896
+ .default(TOOL_TIMEOUT_MAX_MS)
897
+ .meta(meta({
898
+ description: "Ceiling on the time limit an extension tool declares (ToolSpec.timeoutMs) in milliseconds; a longer declared limit is cut to it",
899
+ })),
891
900
  breakerFailures: z
892
901
  .number()
893
902
  .int()
@@ -1025,6 +1034,7 @@ export const KernelConfigSchema = z.strictObject({
1025
1034
  })
1026
1035
  .default({
1027
1036
  timeoutMs: 60000,
1037
+ maxTimeoutMs: TOOL_TIMEOUT_MAX_MS,
1028
1038
  breakerFailures: 5,
1029
1039
  breakerOpenSeconds: 60,
1030
1040
  outputSpillChars: 50000,
@@ -1634,6 +1634,11 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1634
1634
  }, z.core.$strip>>;
1635
1635
  }, z.core.$strip>;
1636
1636
  expiresAt: z.ZodString;
1637
+ open: z.ZodOptional<z.ZodObject<{
1638
+ plugin: z.ZodString;
1639
+ contribution: z.ZodString;
1640
+ item: z.ZodOptional<z.ZodString>;
1641
+ }, z.core.$strip>>;
1637
1642
  }, z.core.$strip>;
1638
1643
  }, z.core.$strip>, z.ZodObject<{
1639
1644
  type: z.ZodLiteral<"question_answered">;
@@ -1416,6 +1416,17 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1416
1416
  questionId: z.string(),
1417
1417
  form: InputFormSchema,
1418
1418
  expiresAt: z.string(),
1419
+ /**
1420
+ * A plugin tool's `InputRequired.open`: a `conversation.panel` of the asking extension the
1421
+ * page opens when the question arrives (display only; the kernel names the plugin itself).
1422
+ */
1423
+ open: z
1424
+ .object({
1425
+ plugin: z.string(),
1426
+ contribution: z.string(),
1427
+ item: z.string().optional(),
1428
+ })
1429
+ .optional(),
1419
1430
  })),
1420
1431
  /**
1421
1432
  * An input request ended: answered, skipped (the run's starter sent a message instead; `answer`