@capybara-hq/kernel 0.1.0-rc.40 → 0.1.0-rc.42
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.
- package/bootstrap.json +10 -1
- package/dist/admin/admin.schemas.d.ts +6 -0
- package/dist/admin/org-network.service.d.ts +3 -1
- package/dist/admin/org-network.service.js +10 -2
- package/dist/app.d.ts +4 -0
- package/dist/app.js +2 -0
- package/dist/background/finish.d.ts +9 -1
- package/dist/background/finish.js +57 -4
- package/dist/background/launch.d.ts +23 -0
- package/dist/background/launch.js +55 -1
- package/dist/background/managed-output.d.ts +110 -0
- package/dist/background/managed-output.js +219 -0
- package/dist/background/managed.d.ts +52 -0
- package/dist/background/managed.js +128 -0
- package/dist/background/poll.job.d.ts +35 -1
- package/dist/background/poll.job.js +174 -9
- package/dist/background/render.js +1 -0
- package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
- package/dist/background/retire-legacy-tasks.job.js +149 -0
- package/dist/background/session.d.ts +15 -5
- package/dist/background/session.js +22 -6
- package/dist/background/stop.d.ts +35 -5
- package/dist/background/stop.js +94 -8
- package/dist/background/store.d.ts +110 -3
- package/dist/background/store.js +205 -3
- package/dist/background/tasks.service.d.ts +18 -1
- package/dist/background/tasks.service.js +99 -9
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/cards.js +1 -1
- package/dist/channels/inbound.js +2 -0
- package/dist/channels/phrases.d.ts +4 -0
- package/dist/channels/phrases.js +4 -0
- package/dist/config/load.d.ts +18 -0
- package/dist/config/load.js +39 -1
- package/dist/config/permission-migration.d.ts +26 -0
- package/dist/config/permission-migration.js +64 -0
- package/dist/config/schema.d.ts +1 -1
- package/dist/config/schema.js +11 -10
- package/dist/conversations/conversations.controller.d.ts +1 -1
- package/dist/conversations/conversations.controller.js +1 -1
- package/dist/conversations/conversations.module.js +12 -0
- package/dist/conversations/conversations.service.d.ts +11 -2
- package/dist/conversations/conversations.service.js +97 -27
- package/dist/conversations/event-log.d.ts +1 -1
- package/dist/conversations/event-log.js +10 -2
- package/dist/conversations/events.d.ts +304 -4
- package/dist/conversations/events.js +279 -29
- package/dist/conversations/permission-profile-store.d.ts +50 -0
- package/dist/conversations/permission-profile-store.js +67 -0
- package/dist/conversations/permission-profile-store.module.d.ts +2 -0
- package/dist/conversations/permission-profile-store.module.js +19 -0
- package/dist/conversations/permission-profiles.controller.d.ts +84 -0
- package/dist/conversations/permission-profiles.controller.js +105 -0
- package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
- package/dist/conversations/permission-profiles.schemas.js +23 -0
- package/dist/conversations/permission-profiles.service.d.ts +56 -0
- package/dist/conversations/permission-profiles.service.js +179 -0
- package/dist/db/kernel-schema.d.ts +238 -3
- package/dist/devices/access.js +1 -1
- package/dist/devices/access.module.d.ts +2 -0
- package/dist/devices/access.module.js +19 -0
- package/dist/devices/conversation-devices.d.ts +8 -29
- package/dist/devices/conversation-devices.js +37 -73
- package/dist/devices/device-projects.service.d.ts +26 -28
- package/dist/devices/device-projects.service.js +123 -127
- package/dist/devices/devices.controller.js +3 -1
- package/dist/devices/devices.module.js +11 -9
- package/dist/devices/devices.service.d.ts +116 -8
- package/dist/devices/devices.service.js +252 -20
- package/dist/devices/dto.d.ts +16 -0
- package/dist/devices/dto.js +34 -6
- package/dist/devices/errors.d.ts +8 -0
- package/dist/devices/errors.js +10 -0
- package/dist/devices/project-rules.d.ts +44 -0
- package/dist/devices/project-rules.js +27 -0
- package/dist/devices/working-root.d.ts +6 -0
- package/dist/devices/working-root.js +12 -1
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +31 -0
- package/dist/evals/reconstruct.d.ts +19 -2
- package/dist/evals/reconstruct.js +40 -2
- package/dist/evals/recorded-permission-context.d.ts +77 -0
- package/dist/evals/recorded-permission-context.js +151 -0
- package/dist/evals/recorded-tools.d.ts +10 -1
- package/dist/evals/recorded-tools.js +27 -3
- package/dist/evals/run-replay.d.ts +8 -2
- package/dist/evals/run-replay.js +18 -2
- package/dist/evals/trajectory.d.ts +1 -1
- package/dist/evals/worker.d.ts +10 -1
- package/dist/evals/worker.js +23 -14
- package/dist/http/api.module.js +2 -0
- package/dist/identity/accounts.d.ts +14 -1
- package/dist/identity/accounts.js +61 -5
- package/dist/identity/identity.module.js +2 -0
- package/dist/identity/settings.d.ts +28 -12
- package/dist/identity/settings.js +89 -33
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
- package/dist/infra/cli/kernel-cli.module.js +5 -2
- package/dist/infra/cli/permission-cutover.d.ts +59 -0
- package/dist/infra/cli/permission-cutover.js +107 -0
- package/dist/infra/config/kernel-config.service.d.ts +2 -2
- package/dist/infra/config/kernel-config.service.js +31 -11
- package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
- package/dist/infra/database/startup-activation-transaction.js +242 -0
- package/dist/infra/database/transaction-host.d.ts +47 -0
- package/dist/infra/database/transaction-host.js +119 -0
- package/dist/infra/database/xact-lock.d.ts +1 -0
- package/dist/infra/database/xact-lock.js +6 -0
- package/dist/infra/outbox/registry.d.ts +39 -0
- package/dist/infra/outbox/registry.js +18 -0
- package/dist/kernel.module.js +2 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +55 -28
- package/dist/local-devices/device-auth.js +1 -1
- package/dist/local-devices/device-policy.service.d.ts +35 -5
- package/dist/local-devices/device-policy.service.js +188 -13
- package/dist/local-devices/instance-bindings.d.ts +82 -0
- package/dist/local-devices/instance-bindings.js +304 -0
- package/dist/local-devices/keys.d.ts +5 -0
- package/dist/local-devices/keys.js +5 -0
- package/dist/local-devices/local-device-gateway.d.ts +19 -4
- package/dist/local-devices/local-device-gateway.js +185 -17
- package/dist/local-devices/local-device-provider.d.ts +42 -7
- package/dist/local-devices/local-device-provider.js +185 -10
- package/dist/local-devices/local-devices.module.d.ts +17 -2
- package/dist/local-devices/local-devices.module.js +49 -8
- package/dist/local-devices/machines.d.ts +35 -12
- package/dist/local-devices/machines.js +203 -8
- package/dist/local-devices/network-grants.js +3 -3
- package/dist/local-devices/network-grants.module.d.ts +2 -0
- package/dist/local-devices/network-grants.module.js +14 -0
- package/dist/local-devices/owner-report.d.ts +79 -0
- package/dist/local-devices/owner-report.js +155 -0
- package/dist/local-devices/owner-reports.d.ts +48 -0
- package/dist/local-devices/owner-reports.js +190 -0
- package/dist/local-devices/policy-summary.d.ts +24 -1
- package/dist/local-devices/policy-summary.js +48 -0
- package/dist/local-devices/relay.d.ts +82 -6
- package/dist/local-devices/relay.js +187 -16
- package/dist/local-devices/targets.d.ts +16 -1
- package/dist/local-devices/targets.js +35 -2
- package/dist/orgs/cloud-network-setting.d.ts +33 -0
- package/dist/orgs/cloud-network-setting.js +47 -0
- package/dist/orgs/offboarding.d.ts +3 -1
- package/dist/orgs/offboarding.js +8 -2
- package/dist/orgs/org-lock.d.ts +10 -4
- package/dist/orgs/org-lock.js +10 -4
- package/dist/orgs/orgs.service.d.ts +3 -1
- package/dist/orgs/orgs.service.js +8 -2
- package/dist/orgs/settings.controller.d.ts +4 -1
- package/dist/orgs/settings.controller.js +3 -3
- package/dist/orgs/settings.service.d.ts +48 -56
- package/dist/orgs/settings.service.js +144 -101
- package/dist/overrides.d.ts +6 -1
- package/dist/overrides.js +2 -0
- package/dist/platform/exclusions.js +20 -0
- package/dist/platform/ops/admin.ops.js +14 -11
- package/dist/platform/ops/agent-skills.ops.js +2 -0
- package/dist/platform/ops/devices.ops.js +10 -2
- package/dist/platform/ops/org-settings.ops.js +6 -6
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/roles/worker.module.js +4 -0
- package/dist/runtime/context/build.d.ts +3 -1
- package/dist/runtime/context/build.js +19 -3
- package/dist/runtime/context/compaction.js +5 -0
- package/dist/runtime/context/device-paths.d.ts +9 -2
- package/dist/runtime/context/device-paths.js +20 -0
- package/dist/runtime/context/permission-profile.d.ts +46 -0
- package/dist/runtime/context/permission-profile.js +194 -0
- package/dist/runtime/maintenance.d.ts +7 -1
- package/dist/runtime/maintenance.js +43 -15
- package/dist/runtime/model-call.d.ts +32 -0
- package/dist/runtime/model-call.js +67 -0
- package/dist/runtime/permission-context-errors.d.ts +39 -0
- package/dist/runtime/permission-context-errors.js +67 -0
- package/dist/runtime/permission-context.service.d.ts +60 -0
- package/dist/runtime/permission-context.service.js +286 -0
- package/dist/runtime/project/knowledge.d.ts +7 -2
- package/dist/runtime/project/knowledge.js +5 -2
- package/dist/runtime/project/knowledge.service.d.ts +17 -2
- package/dist/runtime/project/knowledge.service.js +76 -12
- package/dist/runtime/run-execution.d.ts +4 -1
- package/dist/runtime/run-execution.js +14 -5
- package/dist/runtime/run-steps.d.ts +11 -3
- package/dist/runtime/run-steps.js +27 -4
- package/dist/runtime/runtime.module.js +11 -0
- package/dist/sandbox/attachments-path.d.ts +15 -0
- package/dist/sandbox/attachments-path.js +15 -0
- package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
- package/dist/sandbox/cloud-permission-snapshot.js +407 -0
- package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
- package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
- package/dist/sandbox/held-operations.d.ts +39 -0
- package/dist/sandbox/held-operations.js +119 -0
- package/dist/sandbox/jobs.d.ts +14 -3
- package/dist/sandbox/jobs.js +20 -2
- package/dist/sandbox/kernel-read.d.ts +55 -0
- package/dist/sandbox/kernel-read.js +57 -0
- package/dist/sandbox/legacy-retirement.d.ts +336 -0
- package/dist/sandbox/legacy-retirement.js +1063 -0
- package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
- package/dist/sandbox/legacy-retirement.module.js +25 -0
- package/dist/sandbox/managed-device-context.d.ts +94 -0
- package/dist/sandbox/managed-device-context.js +308 -0
- package/dist/sandbox/managed-device-context.module.d.ts +6 -0
- package/dist/sandbox/managed-device-context.module.js +33 -0
- package/dist/sandbox/modes.d.ts +56 -8
- package/dist/sandbox/modes.js +92 -8
- package/dist/sandbox/operation-authority-types.d.ts +8 -0
- package/dist/sandbox/operation-authority-types.js +32 -0
- package/dist/sandbox/operation-authority.d.ts +145 -0
- package/dist/sandbox/operation-authority.js +783 -0
- package/dist/sandbox/operation-authority.module.d.ts +2 -0
- package/dist/sandbox/operation-authority.module.js +29 -0
- package/dist/sandbox/operation-intents.d.ts +206 -0
- package/dist/sandbox/operation-intents.js +1252 -0
- package/dist/sandbox/operation-intents.module.d.ts +2 -0
- package/dist/sandbox/operation-intents.module.js +21 -0
- package/dist/sandbox/operation-payloads.d.ts +33 -0
- package/dist/sandbox/operation-payloads.js +332 -0
- package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
- package/dist/sandbox/operation-reconcile.job.js +247 -0
- package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
- package/dist/sandbox/permission-authority-epochs.js +83 -0
- package/dist/sandbox/permission-authority-lock.d.ts +38 -0
- package/dist/sandbox/permission-authority-lock.js +147 -0
- package/dist/sandbox/permission-authority.module.d.ts +9 -0
- package/dist/sandbox/permission-authority.module.js +55 -0
- package/dist/sandbox/permission-availability.d.ts +18 -0
- package/dist/sandbox/permission-availability.js +19 -0
- package/dist/sandbox/permission-call-grants.d.ts +34 -0
- package/dist/sandbox/permission-call-grants.js +349 -0
- package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
- package/dist/sandbox/permission-call-grants.module.js +21 -0
- package/dist/sandbox/permission-call-types.d.ts +82 -0
- package/dist/sandbox/permission-call-types.js +1 -0
- package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
- package/dist/sandbox/permission-ceiling-writes.js +223 -0
- package/dist/sandbox/permission-config-publication.d.ts +76 -0
- package/dist/sandbox/permission-config-publication.js +339 -0
- package/dist/sandbox/permission-context-types.d.ts +64 -0
- package/dist/sandbox/permission-context-types.js +24 -0
- package/dist/sandbox/permission-facts.d.ts +206 -0
- package/dist/sandbox/permission-facts.js +627 -0
- package/dist/sandbox/permission-facts.module.d.ts +2 -0
- package/dist/sandbox/permission-facts.module.js +20 -0
- package/dist/sandbox/permission-instance-writes.d.ts +90 -0
- package/dist/sandbox/permission-instance-writes.js +305 -0
- package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
- package/dist/sandbox/permission-runtime-reports.js +354 -0
- package/dist/sandbox/permission-transitions.d.ts +31 -0
- package/dist/sandbox/permission-transitions.js +155 -0
- package/dist/sandbox/platform-full-access.d.ts +128 -0
- package/dist/sandbox/platform-full-access.js +210 -0
- package/dist/sandbox/providers.d.ts +22 -0
- package/dist/sandbox/providers.js +10 -2
- package/dist/sandbox/providers.module.d.ts +2 -0
- package/dist/sandbox/providers.module.js +19 -0
- package/dist/sandbox/request-not-sent.d.ts +13 -0
- package/dist/sandbox/request-not-sent.js +13 -0
- package/dist/sandbox/review/classifier.d.ts +2 -0
- package/dist/sandbox/review/classifier.js +8 -0
- package/dist/sandbox/review/permission-candidate.d.ts +12 -0
- package/dist/sandbox/review/permission-candidate.js +129 -0
- package/dist/sandbox/review/review.service.d.ts +4 -1
- package/dist/sandbox/review/review.service.js +19 -5
- package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
- package/dist/sandbox/sandbox-file-reader.js +51 -7
- package/dist/sandbox/sandbox.module.js +26 -6
- package/dist/sandbox/sandbox.service.d.ts +230 -34
- package/dist/sandbox/sandbox.service.js +1368 -199
- package/dist/sandbox/unreachable.js +17 -3
- package/dist/sandbox/use-context.d.ts +17 -0
- package/dist/sandbox/use-context.js +1 -0
- package/dist/skills/invoke.d.ts +27 -4
- package/dist/skills/invoke.js +72 -7
- package/dist/tools/approvals.controller.d.ts +1 -0
- package/dist/tools/approvals.schemas.d.ts +1 -0
- package/dist/tools/approvals.schemas.js +3 -1
- package/dist/tools/approvals.service.d.ts +23 -10
- package/dist/tools/approvals.service.js +104 -26
- package/dist/tools/builtins/builtin-tools.d.ts +16 -2
- package/dist/tools/builtins/builtin-tools.js +38 -10
- package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
- package/dist/tools/builtins/sandbox/bash.js +201 -5
- package/dist/tools/builtins/sandbox/common.d.ts +92 -20
- package/dist/tools/builtins/sandbox/common.js +201 -17
- package/dist/tools/builtins/sandbox/deliver.js +2 -2
- package/dist/tools/builtins/sandbox/edit.js +2 -2
- package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
- package/dist/tools/builtins/sandbox/glob.js +2 -2
- package/dist/tools/builtins/sandbox/grep.js +2 -2
- package/dist/tools/builtins/sandbox/read.js +2 -2
- package/dist/tools/builtins/sandbox/task-list.js +7 -1
- package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
- package/dist/tools/builtins/sandbox/task-output.js +172 -0
- package/dist/tools/builtins/sandbox/task-stop.js +25 -3
- package/dist/tools/builtins/sandbox/write.js +2 -2
- package/dist/tools/builtins/skill-load.js +9 -6
- package/dist/tools/device-op-resolver.d.ts +1 -1
- package/dist/tools/device-op-resolver.js +13 -3
- package/dist/tools/permission-approval-jobs.d.ts +18 -0
- package/dist/tools/permission-approval-jobs.js +92 -0
- package/dist/tools/pipeline.d.ts +17 -2
- package/dist/tools/pipeline.js +300 -19
- package/dist/tools/registry.d.ts +9 -0
- package/dist/tools/tools.module.js +12 -0
- package/package.json +4 -3
- package/src/migrations/0146_permission_authority_epochs.sql +6 -0
- package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
- package/src/migrations/0148_first_message_request_hash.sql +2 -0
- package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
- package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
- package/src/migrations/0151_starting_execution_grants.sql +8 -0
- package/src/migrations/0152_background_launch_identity.sql +66 -0
- package/src/migrations/0153_background_cancel_requester.sql +13 -0
- package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
- package/src/migrations/0155_device_instance_generations.sql +30 -0
- package/src/migrations/0156_device_owner_report.sql +7 -0
- package/src/migrations/0157_legacy_retirement.sql +116 -0
- package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
- package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
- package/dist/sandbox/platform-auto-mode.d.ts +0 -63
- package/dist/sandbox/platform-auto-mode.js +0 -63
package/dist/background/stop.js
CHANGED
|
@@ -8,13 +8,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
10
|
import { rootsOf } from "@capybara-hq/plugin-sdk";
|
|
11
|
-
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
12
12
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
13
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
14
|
+
import { PERMISSION_CONTEXT_ACTIVATION } from "../sandbox/permission-context-types.js";
|
|
14
15
|
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
15
16
|
import { BackgroundTaskFinisher, } from "./finish.js";
|
|
17
|
+
import { exactRefOf, lastLinesByRef, MANAGED_STOP_GRACE_MS, onManagedInstance, stopEnd, summaryLines, } from "./managed.js";
|
|
16
18
|
import { actingAs, assertTaskRef, decodeTail, killSession, TERM_EXEC_TIMEOUT_MS, tailCommand, taskActor, termScript, } from "./session.js";
|
|
17
|
-
import { BackgroundTaskStore } from "./store.js";
|
|
19
|
+
import { BackgroundTaskStore, isManagedTask, } from "./store.js";
|
|
18
20
|
/** The time limit of reading the last lines after a stop. */
|
|
19
21
|
const TAIL_EXEC_TIMEOUT_MS = 10_000;
|
|
20
22
|
/** How a task that exited by itself ends (spec §4.3): exit 137 past its deadline timed out. */
|
|
@@ -55,12 +57,20 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
55
57
|
sandbox;
|
|
56
58
|
db;
|
|
57
59
|
log;
|
|
58
|
-
|
|
60
|
+
activation;
|
|
61
|
+
constructor(store, finisher, sandbox, db, log,
|
|
62
|
+
/**
|
|
63
|
+
* The paired activation gate: once on, a legacy (SID) task's stop refuses with the retirement
|
|
64
|
+
* refusal exactly when it would run an exec (its instance runs); one whose instance is gone
|
|
65
|
+
* or replaced still finishes without one. A managed task always stops by its exact ref.
|
|
66
|
+
*/
|
|
67
|
+
activation) {
|
|
59
68
|
this.store = store;
|
|
60
69
|
this.finisher = finisher;
|
|
61
70
|
this.sandbox = sandbox;
|
|
62
71
|
this.db = db;
|
|
63
72
|
this.log = log;
|
|
73
|
+
this.activation = activation;
|
|
64
74
|
}
|
|
65
75
|
/**
|
|
66
76
|
* Stops `task` and returns its row afterwards. A task that is no longer running, or that another
|
|
@@ -71,14 +81,17 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
71
81
|
* started the command yet (no `sid`) is only claimed: the launch then kills what it starts and
|
|
72
82
|
* finishes the row `stopped`. When the stop fails while the sandbox runs (busy, a provider
|
|
73
83
|
* error, a session that could not be confirmed empty), the claim is given up, the task stays
|
|
74
|
-
* `running` and the error is thrown.
|
|
84
|
+
* `running` and the error is thrown. `how.reported`: the caller's own result tells the model this
|
|
85
|
+
* finish (a managed task's cancellation settled from a TaskOutput read).
|
|
75
86
|
*/
|
|
76
|
-
async stop(task, why, signal) {
|
|
87
|
+
async stop(task, why, signal, how = {}) {
|
|
77
88
|
if (!(await this.store.claimStop(task.id)))
|
|
78
89
|
return (await this.store.get(task.id)) ?? task;
|
|
79
90
|
// read after the claim: a launch recording its session before the claim is seen here, one
|
|
80
91
|
// recording it after sees the claim (both are single-row updates of the same row)
|
|
81
92
|
const cur = (await this.store.get(task.id)) ?? task;
|
|
93
|
+
if (isManagedTask(cur))
|
|
94
|
+
return this.stopManaged(cur, why, signal, how.reported);
|
|
82
95
|
if (cur.status !== "running" || cur.sid === null || cur.sandboxCreatedAt === null)
|
|
83
96
|
return cur;
|
|
84
97
|
const started = { ...cur, sandboxCreatedAt: cur.sandboxCreatedAt };
|
|
@@ -116,6 +129,76 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
116
129
|
}
|
|
117
130
|
return (await this.store.get(cur.id)) ?? cur;
|
|
118
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* A managed task's stop (permission runtime cutover phase 8.3), claimed by {@link stop}: by its
|
|
134
|
+
* exact ref on its exact instance only, with the five-second grace. The provider's atomically
|
|
135
|
+
* claimed outcome decides the finish: `already-exited` keeps the natural exit, `stopped` is
|
|
136
|
+
* stopped, `lost` is lost (the uncertainty retained), `cancel-pending` writes no finish (the
|
|
137
|
+
* task stays running `cancel-pending`, the claim released, so the poller owes the exact stop
|
|
138
|
+
* again). A task without its ref yet keeps the claim: its dispatch binding settles it unlaunched,
|
|
139
|
+
* or its acknowledgement attaches the ref to an owed cancellation. An instance that is not
|
|
140
|
+
* running (never resumed) or was replaced leaves the cancellation owed. Who asked is recorded,
|
|
141
|
+
* so a later finish keeps their wake rule.
|
|
142
|
+
*/
|
|
143
|
+
async stopManaged(cur, why, signal, reportedHere) {
|
|
144
|
+
if (cur.status !== "running")
|
|
145
|
+
return cur;
|
|
146
|
+
const asker = why === "revoked" ? null : why;
|
|
147
|
+
// the first asker's wake rule holds for the finish, whoever applies the stop
|
|
148
|
+
const by = cur.cancelRequestedBy ?? asker;
|
|
149
|
+
if (cur.executionRef === null) {
|
|
150
|
+
if (asker !== null)
|
|
151
|
+
await this.store.requestCancel(cur.id, asker, false);
|
|
152
|
+
return (await this.store.get(cur.id)) ?? cur;
|
|
153
|
+
}
|
|
154
|
+
// `reportedHere`: the caller's own result tells the model this finish (a TaskOutput read)
|
|
155
|
+
const reported = reportedHere ?? (by === "tool" && why === "tool");
|
|
156
|
+
const stoppedBy = by === "person"
|
|
157
|
+
? "person"
|
|
158
|
+
: by === "conversation_deleted"
|
|
159
|
+
? "deletion"
|
|
160
|
+
: by === "subagent_end"
|
|
161
|
+
? "subagent_end"
|
|
162
|
+
: undefined;
|
|
163
|
+
const opts = stoppedBy === undefined ? {} : { stoppedBy };
|
|
164
|
+
const pending = async () => {
|
|
165
|
+
await this.store.requestCancel(cur.id, asker, true);
|
|
166
|
+
return (await this.store.get(cur.id)) ?? cur;
|
|
167
|
+
};
|
|
168
|
+
let r;
|
|
169
|
+
try {
|
|
170
|
+
exactRefOf(cur);
|
|
171
|
+
await this.store.noteCancelAttempt(cur.id);
|
|
172
|
+
r = await onManagedInstance(this.sandbox.ifRunning.bind(this.sandbox), cur, async (bg, h, ref, sig) => {
|
|
173
|
+
const to = stopEnd(await bg.stop(h, ref, { graceMs: MANAGED_STOP_GRACE_MS, signal: sig }));
|
|
174
|
+
// once the provider claimed the outcome it stands: a failed tail only loses the lines
|
|
175
|
+
const lines = to === null ? "" : summaryLines(await lastLinesByRef(bg, h, ref, sig));
|
|
176
|
+
return { to, lastLines: lines };
|
|
177
|
+
}, signal);
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
await this.store
|
|
181
|
+
.releaseStop(cur.id)
|
|
182
|
+
.catch((e) => this.log.warn("cannot release a background task stop", { taskId: cur.id, err: e }));
|
|
183
|
+
throw err;
|
|
184
|
+
}
|
|
185
|
+
if (r.kind === "ran") {
|
|
186
|
+
if (r.value.to === null)
|
|
187
|
+
return pending();
|
|
188
|
+
await this.finisher.finish(cur, r.value.to, r.value.lastLines, reported, opts);
|
|
189
|
+
}
|
|
190
|
+
else if (r.kind === "not_running") {
|
|
191
|
+
// never resumed for a stop: a suspended instance keeps the cancellation owed; a missing or
|
|
192
|
+
// destroyed one is lost like an acknowledged task's (the uncertain record is retained)
|
|
193
|
+
if (r.status === "suspended")
|
|
194
|
+
return pending();
|
|
195
|
+
await this.finisher.finish(cur, notRunningAs(r.status, false), "", reported, opts);
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
await this.finisher.finish(cur, RECREATED, "", reported, opts);
|
|
199
|
+
}
|
|
200
|
+
return (await this.store.get(cur.id)) ?? cur;
|
|
201
|
+
}
|
|
119
202
|
/**
|
|
120
203
|
* SIGTERM, the grace period, SIGKILL until the session is empty, then the last lines: in the
|
|
121
204
|
* task's own instance only (`ifRunning`); a task from before devices has none.
|
|
@@ -124,7 +207,8 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
124
207
|
if (cur.deviceId === null)
|
|
125
208
|
return { kind: "not_running", status: "gone" };
|
|
126
209
|
return this.sandbox.ifRunning(cur.deviceId, { createdAt: cur.sandboxCreatedAt }, async (tp, h, sig) => {
|
|
127
|
-
|
|
210
|
+
// once activated this refuses before the provider (the retirement gate owns the task)
|
|
211
|
+
const p = actingAs(tp, taskActor(cur), this.activation);
|
|
128
212
|
const term = await p.exec(h, {
|
|
129
213
|
command: termScript(cur.id, sid),
|
|
130
214
|
cwd: rootsOf(h).workspace,
|
|
@@ -137,7 +221,7 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
|
|
|
137
221
|
throw new Error(`the stop of background task ${cur.id} failed (${term.exitCode})`);
|
|
138
222
|
}
|
|
139
223
|
// also after an exit: processes the command left running are stopped with the task
|
|
140
|
-
if (!(await killSession(p, h, sid))) {
|
|
224
|
+
if (!(await killSession(p, h, sid, this.activation))) {
|
|
141
225
|
throw new Error(`background task ${cur.id} could not be confirmed stopped`);
|
|
142
226
|
}
|
|
143
227
|
const tail = await p.exec(h, {
|
|
@@ -219,6 +303,8 @@ BackgroundTaskStopper = __decorate([
|
|
|
219
303
|
__param(1, Inject(BackgroundTaskFinisher)),
|
|
220
304
|
__param(2, Inject(SandboxService)),
|
|
221
305
|
__param(3, Inject(KernelDb)),
|
|
222
|
-
__param(4, Inject(KERNEL_LOGGER))
|
|
306
|
+
__param(4, Inject(KERNEL_LOGGER)),
|
|
307
|
+
__param(5, Optional()),
|
|
308
|
+
__param(5, Inject(PERMISSION_CONTEXT_ACTIVATION))
|
|
223
309
|
], BackgroundTaskStopper);
|
|
224
310
|
export { BackgroundTaskStopper };
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { SandboxExecutionRef } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { BackgroundLaunchState } from "../db/kernel-schema.js";
|
|
1
3
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
2
4
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
3
5
|
import { BackgroundLaunchLock } from "./launch-lock.js";
|
|
@@ -50,8 +52,62 @@ export interface BackgroundTaskRow {
|
|
|
50
52
|
readOffset: number;
|
|
51
53
|
/** When a stop claimed the task ({@link BackgroundTaskStore.claimStop}); null otherwise. */
|
|
52
54
|
stoppingAt: Date | null;
|
|
55
|
+
/** `legacy` for SID-launched rows; a managed launch's durable state otherwise (0152). */
|
|
56
|
+
launchState: BackgroundLaunchState;
|
|
57
|
+
/** A managed task's stable start operation (null for legacy rows). */
|
|
58
|
+
operationId: string | null;
|
|
59
|
+
/** A managed task's trusted working root, persisted before dispatch. */
|
|
60
|
+
workingRoot: string | null;
|
|
61
|
+
/** A managed task's output retention deadline, part of its start input. */
|
|
62
|
+
retainUntil: Date | null;
|
|
63
|
+
/** The exact typed start result; never inferred from a SID, PID or path. */
|
|
64
|
+
executionRef: SandboxExecutionRef | null;
|
|
65
|
+
/** A managed task's held instance (its handle id), bound at dispatch. */
|
|
66
|
+
instanceId: string | null;
|
|
67
|
+
/** A managed task's exact instance generation (its `created_at` in ms), bound at dispatch. */
|
|
68
|
+
instanceGeneration: string | null;
|
|
69
|
+
/** When a managed task's cancellation was asked for (a stop or a revocation). */
|
|
70
|
+
cancelRequestedAt: Date | null;
|
|
71
|
+
/** Who asked for it by a stop (0153); null for a revocation's cancellation or none. */
|
|
72
|
+
cancelRequestedBy: CancelRequester | null;
|
|
53
73
|
}
|
|
54
|
-
|
|
74
|
+
/** Who asked for a managed task's stop: their wake rule holds for its later finish. */
|
|
75
|
+
export type CancelRequester = "tool" | "person" | "conversation_deleted" | "subagent_end";
|
|
76
|
+
/** Whether `task` is a managed (exact-ref) task rather than a legacy SID one. */
|
|
77
|
+
export declare const isManagedTask: (task: Pick<BackgroundTaskRow, "launchState">) => boolean;
|
|
78
|
+
/** A managed launch's reservation: everything known before the start is dispatched. */
|
|
79
|
+
export interface ManagedTaskReservation {
|
|
80
|
+
id: string;
|
|
81
|
+
orgId: string;
|
|
82
|
+
conversationId: string;
|
|
83
|
+
sandboxConversationId: string;
|
|
84
|
+
deviceId: string;
|
|
85
|
+
runId: string;
|
|
86
|
+
callId: string;
|
|
87
|
+
triggerAccountId: string;
|
|
88
|
+
description: string;
|
|
89
|
+
command: string;
|
|
90
|
+
operationId: string;
|
|
91
|
+
workingRoot: string;
|
|
92
|
+
/** Absolute: `${workingRoot}/.capybara/tasks/${id}.out`. */
|
|
93
|
+
outputPath: string;
|
|
94
|
+
startedAt: Date;
|
|
95
|
+
deadlineAt: Date;
|
|
96
|
+
retainUntil: Date;
|
|
97
|
+
}
|
|
98
|
+
/** {@link BackgroundTaskStore.reserveManaged}'s answer. */
|
|
99
|
+
export type ManagedReservation = {
|
|
100
|
+
kind: "reserved";
|
|
101
|
+
row: BackgroundTaskRow;
|
|
102
|
+
}
|
|
103
|
+
/** The same run call reserved before (a retry): its persisted identity is reused as it is. */
|
|
104
|
+
| {
|
|
105
|
+
kind: "existing";
|
|
106
|
+
row: BackgroundTaskRow;
|
|
107
|
+
} | {
|
|
108
|
+
kind: "full";
|
|
109
|
+
};
|
|
110
|
+
export type BackgroundTaskInsert = Omit<BackgroundTaskRow, "status" | "finishedAt" | "exitCode" | "lostReason" | "killPending" | "readOffset" | "stoppingAt" | "launchState" | "operationId" | "workingRoot" | "retainUntil" | "executionRef" | "instanceId" | "instanceGeneration" | "cancelRequestedAt" | "cancelRequestedBy">;
|
|
55
111
|
/** A launch's reservation: the row before the command started (no `sid`, no instance yet). */
|
|
56
112
|
export type BackgroundTaskReservation = Omit<BackgroundTaskInsert, "sid" | "sandboxCreatedAt">;
|
|
57
113
|
/**
|
|
@@ -83,6 +139,20 @@ export declare class BackgroundTaskStore {
|
|
|
83
139
|
* `maxTasks` run. False (nothing written) when that conversation tree already runs `maxTasks`.
|
|
84
140
|
*/
|
|
85
141
|
reserve(row: BackgroundTaskReservation, maxTasks: number): Promise<boolean>;
|
|
142
|
+
/**
|
|
143
|
+
* Reserves a managed launch (permission runtime cutover phase 8.2) under the root conversation's
|
|
144
|
+
* launch lock, before anything is dispatched: the task id, its stable operation id, the
|
|
145
|
+
* working root, the absolute artifact path, the deadline and the retention deadline. A retry of
|
|
146
|
+
* the same run call (same `runId` / `callId`) gets the row it reserved before, unchanged, so the
|
|
147
|
+
* start input and its hash stay the same; it never takes a second slot of `maxTasks`.
|
|
148
|
+
*/
|
|
149
|
+
reserveManaged(row: ManagedTaskReservation, maxTasks: number): Promise<ManagedReservation>;
|
|
150
|
+
/**
|
|
151
|
+
* Fails a managed reservation that provably never dispatched (`pending`): `failed`, `terminal`,
|
|
152
|
+
* when `executionId` is still the run's current execution claim.
|
|
153
|
+
* A dispatched row is never failed here: a null reference is no proof that nothing launched.
|
|
154
|
+
*/
|
|
155
|
+
failManagedPreEffect(id: string, reason: string, executionId: string): Promise<boolean>;
|
|
86
156
|
/**
|
|
87
157
|
* Records the started command of a reserved row: `started`, or `stopping` when a stop claimed the
|
|
88
158
|
* reservation meanwhile (the launch then kills the command and finishes the row with
|
|
@@ -127,7 +197,18 @@ export declare class BackgroundTaskStore {
|
|
|
127
197
|
conversationId: string;
|
|
128
198
|
sandboxConversationId: string;
|
|
129
199
|
}[]>;
|
|
130
|
-
|
|
200
|
+
/**
|
|
201
|
+
* Inserts a legacy row. `legacyDispatch` (0157) defaults to `unknown`: a row is "never
|
|
202
|
+
* dispatched" only when its reservation says so.
|
|
203
|
+
*/
|
|
204
|
+
insert(row: BackgroundTaskInsert, legacyDispatch?: "unknown" | "reserved"): Promise<void>;
|
|
205
|
+
/** The managed task launched by start operation `operationId`, if its row still exists. */
|
|
206
|
+
byOperation(operationId: string): Promise<BackgroundTaskRow | undefined>;
|
|
207
|
+
/**
|
|
208
|
+
* A finished managed task whose owed cancellation was later established by its exact ref (the
|
|
209
|
+
* revoke worker): its record becomes `terminal`. Its finish and event stay as they were.
|
|
210
|
+
*/
|
|
211
|
+
settleOwedCancel(id: string): Promise<void>;
|
|
131
212
|
get(id: string): Promise<BackgroundTaskRow | undefined>;
|
|
132
213
|
/** The running tasks of one root conversation's tree, oldest first. */
|
|
133
214
|
runningIn(sandboxConversationId: string): Promise<BackgroundTaskRow[]>;
|
|
@@ -137,6 +218,27 @@ export declare class BackgroundTaskStore {
|
|
|
137
218
|
* left to its launch, a claimed task to its stop.
|
|
138
219
|
*/
|
|
139
220
|
runningStarted(): Promise<BackgroundTaskRow[]>;
|
|
221
|
+
/**
|
|
222
|
+
* Every running acknowledged managed task with no live stop claim, oldest first: what the
|
|
223
|
+
* poller checks by exact status.
|
|
224
|
+
*/
|
|
225
|
+
runningManaged(): Promise<BackgroundTaskRow[]>;
|
|
226
|
+
/**
|
|
227
|
+
* The running managed tasks that owe an exact stop (`cancel-pending` with a ref, no live stop
|
|
228
|
+
* claim), least recently attempted first. A task whose recorded instance is suspended is left
|
|
229
|
+
* out: a stop never resumes it, so it cannot progress there.
|
|
230
|
+
*/
|
|
231
|
+
owedCancels(): Promise<BackgroundTaskRow[]>;
|
|
232
|
+
/** Records that an exact stop of the task is being attempted now (its owed-stop turn moves back). */
|
|
233
|
+
noteCancelAttempt(id: string): Promise<void>;
|
|
234
|
+
/**
|
|
235
|
+
* Records who asked for a running managed task's stop (the first asker is kept) and when. With
|
|
236
|
+
* `release` (the stop could not settle now: the provider recorded a pending cancellation, or the
|
|
237
|
+
* instance is not reachable) an acknowledged task becomes `cancel-pending` and the stop's claim
|
|
238
|
+
* is given up, so the poller owes the exact stop; without, the claim stays (a task without its
|
|
239
|
+
* ref yet: the dispatch binding or the acknowledgement turns the claim into the owed cancel).
|
|
240
|
+
*/
|
|
241
|
+
requestCancel(id: string, by: CancelRequester | null, release: boolean): Promise<void>;
|
|
140
242
|
/** The running tasks one conversation owns (not those of its sub-agents), oldest first. */
|
|
141
243
|
runningOwnedBy(conversationId: string): Promise<BackgroundTaskRow[]>;
|
|
142
244
|
/**
|
|
@@ -163,6 +265,7 @@ export declare class BackgroundTaskStore {
|
|
|
163
265
|
killPending?: boolean;
|
|
164
266
|
}, opts?: {
|
|
165
267
|
unclaimed?: boolean;
|
|
268
|
+
managed?: "terminal" | "cancel-pending";
|
|
166
269
|
}): Promise<boolean>;
|
|
167
270
|
/** Moves the read offset forward only (a concurrent reader never moves it back). */
|
|
168
271
|
advanceOffset(id: string, to: number): Promise<void>;
|
|
@@ -172,6 +275,10 @@ export declare class BackgroundTaskStore {
|
|
|
172
275
|
*/
|
|
173
276
|
pendingKills(deviceId: string): Promise<BackgroundTaskRow[]>;
|
|
174
277
|
clearKill(ids: string[]): Promise<void>;
|
|
175
|
-
/**
|
|
278
|
+
/**
|
|
279
|
+
* Deletes finished tasks that ended before `before`; a running one is never deleted, nor a
|
|
280
|
+
* managed record whose launch or cancellation is still uncertain (only `legacy` and settled
|
|
281
|
+
* `terminal` rows go).
|
|
282
|
+
*/
|
|
176
283
|
pruneFinished(before: Date): Promise<number>;
|
|
177
284
|
}
|
package/dist/background/store.js
CHANGED
|
@@ -15,6 +15,8 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
|
15
15
|
import { BackgroundLaunchLock } from "./launch-lock.js";
|
|
16
16
|
/** The status of a task that is still live; the one filter every "running tasks" read shares. */
|
|
17
17
|
export const RUNNING_TASK_STATUS = "running";
|
|
18
|
+
/** Whether `task` is a managed (exact-ref) task rather than a legacy SID one. */
|
|
19
|
+
export const isManagedTask = (task) => task.launchState !== "legacy";
|
|
18
20
|
const toRow = (r) => ({
|
|
19
21
|
id: r.id,
|
|
20
22
|
orgId: r.org_id,
|
|
@@ -38,6 +40,15 @@ const toRow = (r) => ({
|
|
|
38
40
|
killPending: r.kill_pending,
|
|
39
41
|
readOffset: Number(r.read_offset),
|
|
40
42
|
stoppingAt: r.stopping_at === null ? null : new Date(r.stopping_at),
|
|
43
|
+
launchState: r.launch_state,
|
|
44
|
+
operationId: r.operation_id,
|
|
45
|
+
workingRoot: r.working_root,
|
|
46
|
+
retainUntil: r.retain_until === null ? null : new Date(r.retain_until),
|
|
47
|
+
executionRef: r.execution_ref,
|
|
48
|
+
instanceId: r.instance_id,
|
|
49
|
+
instanceGeneration: r.instance_generation,
|
|
50
|
+
cancelRequestedAt: r.cancel_requested_at === null ? null : new Date(r.cancel_requested_at),
|
|
51
|
+
cancelRequestedBy: r.cancel_requested_by,
|
|
41
52
|
});
|
|
42
53
|
/**
|
|
43
54
|
* How long a stop's claim holds: a claim older than this is abandoned (its stopper died), so the
|
|
@@ -77,9 +88,83 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
77
88
|
await this.launchLock.lock(row.sandboxConversationId);
|
|
78
89
|
if ((await this.countRunning(row.sandboxConversationId)) >= maxTasks)
|
|
79
90
|
return false;
|
|
80
|
-
|
|
91
|
+
// not admitted for dispatch yet (0157): the launch's freeze check marks it `dispatched`
|
|
92
|
+
await this.insert({ ...row, sid: null, sandboxCreatedAt: null }, "reserved");
|
|
81
93
|
return true;
|
|
82
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Reserves a managed launch (permission runtime cutover phase 8.2) under the root conversation's
|
|
97
|
+
* launch lock, before anything is dispatched: the task id, its stable operation id, the
|
|
98
|
+
* working root, the absolute artifact path, the deadline and the retention deadline. A retry of
|
|
99
|
+
* the same run call (same `runId` / `callId`) gets the row it reserved before, unchanged, so the
|
|
100
|
+
* start input and its hash stay the same; it never takes a second slot of `maxTasks`.
|
|
101
|
+
*/
|
|
102
|
+
async reserveManaged(row, maxTasks) {
|
|
103
|
+
await this.launchLock.lock(row.sandboxConversationId);
|
|
104
|
+
const previous = await this.db
|
|
105
|
+
.selectFrom("background_tasks")
|
|
106
|
+
.selectAll()
|
|
107
|
+
.where("run_id", "=", row.runId)
|
|
108
|
+
.where("call_id", "=", row.callId)
|
|
109
|
+
.where("launch_state", "<>", "legacy")
|
|
110
|
+
.executeTakeFirst();
|
|
111
|
+
if (previous)
|
|
112
|
+
return { kind: "existing", row: toRow(previous) };
|
|
113
|
+
if ((await this.countRunning(row.sandboxConversationId)) >= maxTasks)
|
|
114
|
+
return { kind: "full" };
|
|
115
|
+
const inserted = await this.db
|
|
116
|
+
.insertInto("background_tasks")
|
|
117
|
+
.values({
|
|
118
|
+
id: row.id,
|
|
119
|
+
org_id: row.orgId,
|
|
120
|
+
conversation_id: row.conversationId,
|
|
121
|
+
sandbox_conversation_id: row.sandboxConversationId,
|
|
122
|
+
device_id: row.deviceId,
|
|
123
|
+
run_id: row.runId,
|
|
124
|
+
call_id: row.callId,
|
|
125
|
+
trigger_account_id: row.triggerAccountId,
|
|
126
|
+
description: row.description,
|
|
127
|
+
command: row.command,
|
|
128
|
+
sid: null,
|
|
129
|
+
output_path: row.outputPath,
|
|
130
|
+
started_at: row.startedAt,
|
|
131
|
+
deadline_at: row.deadlineAt,
|
|
132
|
+
sandbox_created_at: null,
|
|
133
|
+
launch_state: "pending",
|
|
134
|
+
operation_id: row.operationId,
|
|
135
|
+
working_root: row.workingRoot,
|
|
136
|
+
retain_until: row.retainUntil,
|
|
137
|
+
})
|
|
138
|
+
.returningAll()
|
|
139
|
+
.executeTakeFirstOrThrow();
|
|
140
|
+
return { kind: "reserved", row: toRow(inserted) };
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Fails a managed reservation that provably never dispatched (`pending`): `failed`, `terminal`,
|
|
144
|
+
* when `executionId` is still the run's current execution claim.
|
|
145
|
+
* A dispatched row is never failed here: a null reference is no proof that nothing launched.
|
|
146
|
+
*/
|
|
147
|
+
async failManagedPreEffect(id, reason, executionId) {
|
|
148
|
+
const r = await this.db
|
|
149
|
+
.updateTable("background_tasks")
|
|
150
|
+
.set({
|
|
151
|
+
status: "failed",
|
|
152
|
+
launch_state: "terminal",
|
|
153
|
+
finished_at: sql `now()`,
|
|
154
|
+
lost_reason: reason,
|
|
155
|
+
stopping_at: null,
|
|
156
|
+
})
|
|
157
|
+
.where("id", "=", id)
|
|
158
|
+
.where("status", "=", "running")
|
|
159
|
+
.where("launch_state", "=", "pending")
|
|
160
|
+
// only the run's current execution claim settles it: a stale one never fails the retry
|
|
161
|
+
.where(({ exists, selectFrom }) => exists(selectFrom("runs")
|
|
162
|
+
.select("runs.id")
|
|
163
|
+
.whereRef("runs.id", "=", "background_tasks.run_id")
|
|
164
|
+
.where("runs.execution_id", "=", executionId)))
|
|
165
|
+
.executeTakeFirst();
|
|
166
|
+
return Number(r.numUpdatedRows) > 0;
|
|
167
|
+
}
|
|
83
168
|
/**
|
|
84
169
|
* Records the started command of a reserved row: `started`, or `stopping` when a stop claimed the
|
|
85
170
|
* reservation meanwhile (the launch then kills the command and finishes the row with
|
|
@@ -96,6 +181,7 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
96
181
|
.where("id", "=", id)
|
|
97
182
|
.where("status", "=", "running")
|
|
98
183
|
.where("sid", "is", null)
|
|
184
|
+
.where("launch_state", "=", "legacy")
|
|
99
185
|
.returning("stopping_at")
|
|
100
186
|
.executeTakeFirst();
|
|
101
187
|
if (!r)
|
|
@@ -156,6 +242,8 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
156
242
|
.where("status", "=", "running")
|
|
157
243
|
// only a reservation that never started: a row with its sid is tracked by the poller
|
|
158
244
|
.where("sid", "is", null)
|
|
245
|
+
// a managed row settles through its durable launch state only
|
|
246
|
+
.where("launch_state", "=", "legacy")
|
|
159
247
|
.execute();
|
|
160
248
|
}
|
|
161
249
|
/**
|
|
@@ -176,9 +264,14 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
176
264
|
finished_at: sql `now()`,
|
|
177
265
|
lost_reason: "launch_abandoned",
|
|
178
266
|
stopping_at: null,
|
|
267
|
+
// a managed reservation that never dispatched settles; dispatch is conditional on
|
|
268
|
+
// `pending`, so a launch racing this update either wins or is refused before effects
|
|
269
|
+
launch_state: sql `CASE WHEN launch_state = 'pending' THEN 'terminal' ELSE launch_state END`,
|
|
179
270
|
})
|
|
180
271
|
.where("status", "=", "running")
|
|
181
272
|
.where("sid", "is", null)
|
|
273
|
+
// never a dispatched, acknowledged or cancel-pending managed task
|
|
274
|
+
.where("launch_state", "in", ["legacy", "pending"])
|
|
182
275
|
.where(unclaimed)
|
|
183
276
|
.where("started_at", "<", before)
|
|
184
277
|
.returning(["id", "conversation_id", "sandbox_conversation_id"])
|
|
@@ -189,10 +282,15 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
189
282
|
sandboxConversationId: x.sandbox_conversation_id,
|
|
190
283
|
}));
|
|
191
284
|
}
|
|
192
|
-
|
|
285
|
+
/**
|
|
286
|
+
* Inserts a legacy row. `legacyDispatch` (0157) defaults to `unknown`: a row is "never
|
|
287
|
+
* dispatched" only when its reservation says so.
|
|
288
|
+
*/
|
|
289
|
+
async insert(row, legacyDispatch = "unknown") {
|
|
193
290
|
await this.db
|
|
194
291
|
.insertInto("background_tasks")
|
|
195
292
|
.values({
|
|
293
|
+
legacy_dispatch: legacyDispatch,
|
|
196
294
|
id: row.id,
|
|
197
295
|
org_id: row.orgId,
|
|
198
296
|
conversation_id: row.conversationId,
|
|
@@ -211,6 +309,28 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
211
309
|
})
|
|
212
310
|
.execute();
|
|
213
311
|
}
|
|
312
|
+
/** The managed task launched by start operation `operationId`, if its row still exists. */
|
|
313
|
+
async byOperation(operationId) {
|
|
314
|
+
const r = await this.db
|
|
315
|
+
.selectFrom("background_tasks")
|
|
316
|
+
.selectAll()
|
|
317
|
+
.where("operation_id", "=", operationId)
|
|
318
|
+
.executeTakeFirst();
|
|
319
|
+
return r === undefined ? undefined : toRow(r);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* A finished managed task whose owed cancellation was later established by its exact ref (the
|
|
323
|
+
* revoke worker): its record becomes `terminal`. Its finish and event stay as they were.
|
|
324
|
+
*/
|
|
325
|
+
async settleOwedCancel(id) {
|
|
326
|
+
await this.db
|
|
327
|
+
.updateTable("background_tasks")
|
|
328
|
+
.set({ launch_state: "terminal" })
|
|
329
|
+
.where("id", "=", id)
|
|
330
|
+
.where("status", "<>", "running")
|
|
331
|
+
.where("launch_state", "=", "cancel-pending")
|
|
332
|
+
.execute();
|
|
333
|
+
}
|
|
214
334
|
async get(id) {
|
|
215
335
|
const r = await this.db
|
|
216
336
|
.selectFrom("background_tasks")
|
|
@@ -248,6 +368,75 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
248
368
|
.execute();
|
|
249
369
|
return rows.map(toRow);
|
|
250
370
|
}
|
|
371
|
+
/**
|
|
372
|
+
* Every running acknowledged managed task with no live stop claim, oldest first: what the
|
|
373
|
+
* poller checks by exact status.
|
|
374
|
+
*/
|
|
375
|
+
async runningManaged() {
|
|
376
|
+
const rows = await this.db
|
|
377
|
+
.selectFrom("background_tasks")
|
|
378
|
+
.selectAll()
|
|
379
|
+
.where("status", "=", "running")
|
|
380
|
+
.where("launch_state", "=", "acknowledged")
|
|
381
|
+
.where("execution_ref", "is not", null)
|
|
382
|
+
.where(unclaimed)
|
|
383
|
+
.orderBy("started_at", "asc")
|
|
384
|
+
.orderBy("id", "asc")
|
|
385
|
+
.execute();
|
|
386
|
+
return rows.map(toRow);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* The running managed tasks that owe an exact stop (`cancel-pending` with a ref, no live stop
|
|
390
|
+
* claim), least recently attempted first. A task whose recorded instance is suspended is left
|
|
391
|
+
* out: a stop never resumes it, so it cannot progress there.
|
|
392
|
+
*/
|
|
393
|
+
async owedCancels() {
|
|
394
|
+
const rows = await this.db
|
|
395
|
+
.selectFrom("background_tasks")
|
|
396
|
+
.selectAll("background_tasks")
|
|
397
|
+
.leftJoin("device_instances", "device_instances.device_id", "background_tasks.device_id")
|
|
398
|
+
.where("background_tasks.status", "=", "running")
|
|
399
|
+
.where("background_tasks.launch_state", "=", "cancel-pending")
|
|
400
|
+
.where("background_tasks.execution_ref", "is not", null)
|
|
401
|
+
.where(sql `(background_tasks.stopping_at IS NULL OR background_tasks.stopping_at < now() - ${STOP_CLAIM_TTL_MS}::integer * interval '1 millisecond')`)
|
|
402
|
+
.where(sql `NOT (device_instances.status IS NOT DISTINCT FROM 'suspended' AND floor(extract(epoch from device_instances.created_at) * 1000)::bigint::text = background_tasks.instance_generation)`)
|
|
403
|
+
.orderBy(sql `background_tasks.cancel_attempted_at ASC NULLS FIRST`)
|
|
404
|
+
.orderBy("background_tasks.started_at", "asc")
|
|
405
|
+
.orderBy("background_tasks.id", "asc")
|
|
406
|
+
.execute();
|
|
407
|
+
return rows.map(toRow);
|
|
408
|
+
}
|
|
409
|
+
/** Records that an exact stop of the task is being attempted now (its owed-stop turn moves back). */
|
|
410
|
+
async noteCancelAttempt(id) {
|
|
411
|
+
await this.db
|
|
412
|
+
.updateTable("background_tasks")
|
|
413
|
+
.set({ cancel_attempted_at: sql `now()` })
|
|
414
|
+
.where("id", "=", id)
|
|
415
|
+
.execute();
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Records who asked for a running managed task's stop (the first asker is kept) and when. With
|
|
419
|
+
* `release` (the stop could not settle now: the provider recorded a pending cancellation, or the
|
|
420
|
+
* instance is not reachable) an acknowledged task becomes `cancel-pending` and the stop's claim
|
|
421
|
+
* is given up, so the poller owes the exact stop; without, the claim stays (a task without its
|
|
422
|
+
* ref yet: the dispatch binding or the acknowledgement turns the claim into the owed cancel).
|
|
423
|
+
*/
|
|
424
|
+
async requestCancel(id, by, release) {
|
|
425
|
+
await this.db
|
|
426
|
+
.updateTable("background_tasks")
|
|
427
|
+
.set({
|
|
428
|
+
cancel_requested_by: sql `COALESCE(cancel_requested_by, ${by}::text)`,
|
|
429
|
+
cancel_requested_at: sql `COALESCE(cancel_requested_at, now())`,
|
|
430
|
+
...(release && {
|
|
431
|
+
stopping_at: null,
|
|
432
|
+
launch_state: sql `CASE WHEN launch_state = 'acknowledged' THEN 'cancel-pending' ELSE launch_state END`,
|
|
433
|
+
}),
|
|
434
|
+
})
|
|
435
|
+
.where("id", "=", id)
|
|
436
|
+
.where("status", "=", "running")
|
|
437
|
+
.where("launch_state", "<>", "legacy")
|
|
438
|
+
.execute();
|
|
439
|
+
}
|
|
251
440
|
/** The running tasks one conversation owns (not those of its sub-agents), oldest first. */
|
|
252
441
|
async runningOwnedBy(conversationId) {
|
|
253
442
|
const rows = await this.db
|
|
@@ -322,6 +511,11 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
322
511
|
lost_reason: to.lostReason ?? null,
|
|
323
512
|
stopping_at: null,
|
|
324
513
|
...(to.killPending !== undefined && { kill_pending: to.killPending }),
|
|
514
|
+
// a managed task's settlement: `terminal` only on verified evidence; an uncertain end
|
|
515
|
+
// (lost) keeps its owed cancellation record
|
|
516
|
+
...(opts.managed !== undefined && {
|
|
517
|
+
launch_state: sql `CASE WHEN launch_state = 'legacy' THEN 'legacy' ELSE ${opts.managed} END`,
|
|
518
|
+
}),
|
|
325
519
|
})
|
|
326
520
|
.where("id", "=", id)
|
|
327
521
|
.where("status", "=", "running");
|
|
@@ -362,11 +556,16 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
362
556
|
.where("id", "in", ids)
|
|
363
557
|
.execute();
|
|
364
558
|
}
|
|
365
|
-
/**
|
|
559
|
+
/**
|
|
560
|
+
* Deletes finished tasks that ended before `before`; a running one is never deleted, nor a
|
|
561
|
+
* managed record whose launch or cancellation is still uncertain (only `legacy` and settled
|
|
562
|
+
* `terminal` rows go).
|
|
563
|
+
*/
|
|
366
564
|
async pruneFinished(before) {
|
|
367
565
|
const r = await this.db
|
|
368
566
|
.deleteFrom("background_tasks")
|
|
369
567
|
.where("status", "<>", "running")
|
|
568
|
+
.where("launch_state", "in", ["legacy", "terminal"])
|
|
370
569
|
.where("finished_at", "<", before)
|
|
371
570
|
.executeTakeFirst();
|
|
372
571
|
return Number(r.numDeletedRows);
|
|
@@ -375,6 +574,9 @@ let BackgroundTaskStore = class BackgroundTaskStore {
|
|
|
375
574
|
__decorate([
|
|
376
575
|
Transactional()
|
|
377
576
|
], BackgroundTaskStore.prototype, "reserve", null);
|
|
577
|
+
__decorate([
|
|
578
|
+
Transactional()
|
|
579
|
+
], BackgroundTaskStore.prototype, "reserveManaged", null);
|
|
378
580
|
__decorate([
|
|
379
581
|
Transactional({ propagation: "mandatory" })
|
|
380
582
|
], BackgroundTaskStore.prototype, "finish", null);
|
|
@@ -63,7 +63,17 @@ export declare class BackgroundTasks {
|
|
|
63
63
|
private readonly eventLog;
|
|
64
64
|
private readonly db;
|
|
65
65
|
private readonly devices;
|
|
66
|
-
|
|
66
|
+
/**
|
|
67
|
+
* The paired activation gate: once on, a legacy (SID) task is never read or stopped by a raw
|
|
68
|
+
* exec (the retirement gate owns it); a managed task always goes by its exact ref.
|
|
69
|
+
*/
|
|
70
|
+
private readonly activation?;
|
|
71
|
+
constructor(access: Pick<ConversationAccess, "isAccessible">, store: Pick<BackgroundTaskStore, "listFor" | "get">, stopper: Pick<BackgroundTaskStopper, "stop">, sandbox: Pick<SandboxService, "availableFor" | "ifRunning">, eventLog: Pick<EventLog, "findByIdem">, db: KernelDb, devices: Pick<ConversationDevices, "forTool">,
|
|
72
|
+
/**
|
|
73
|
+
* The paired activation gate: once on, a legacy (SID) task is never read or stopped by a raw
|
|
74
|
+
* exec (the retirement gate owns it); a managed task always goes by its exact ref.
|
|
75
|
+
*/
|
|
76
|
+
activation?: boolean | undefined);
|
|
67
77
|
/**
|
|
68
78
|
* The conversation and every sub-agent conversation below it (grandchildren too: their tasks run
|
|
69
79
|
* in the root's sandbox, agent map spec §6); `conversation.not_found` when not visible.
|
|
@@ -95,6 +105,13 @@ export declare class BackgroundTasks {
|
|
|
95
105
|
private environmentOf;
|
|
96
106
|
/** Reads the output from the task's running instance, or says why it cannot. */
|
|
97
107
|
private readLive;
|
|
108
|
+
/**
|
|
109
|
+
* A managed task's live suffix (permission runtime cutover phase 8.3): by its exact ref on its
|
|
110
|
+
* exact instance only (never resumed, no exec, no path), the metadata total N first, then every
|
|
111
|
+
* byte of the last `tail` bytes before N through bounded reads; N stays the end however the
|
|
112
|
+
* output grows meanwhile. The task's ref is loaded from its authorized row, never supplied.
|
|
113
|
+
*/
|
|
114
|
+
private readManaged;
|
|
98
115
|
}
|
|
99
116
|
/**
|
|
100
117
|
* Prints `size <bytes>` and `out <base64 of the last `tail` bytes>`, or `missing` when the output
|