@cloudflare/think 0.18.0 → 0.19.0
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/dist/{index-CJ--4uax.d.ts → index-BLkPlEbF.d.ts} +126 -56
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +1 -1
- package/dist/think.js +464 -387
- package/dist/think.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/package.json +3 -3
package/dist/think.js
CHANGED
|
@@ -1082,9 +1082,38 @@ function isAction(value) {
|
|
|
1082
1082
|
return typeof value === "object" && value !== null && value[ACTION_BRAND] === true;
|
|
1083
1083
|
}
|
|
1084
1084
|
const admittedTurnContext = new AsyncLocalStorage();
|
|
1085
|
+
const recoveredTurnAcceptanceContext = new AsyncLocalStorage();
|
|
1085
1086
|
const inferenceStreamFinalizers = /* @__PURE__ */ new WeakMap();
|
|
1086
1087
|
const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
|
|
1087
|
-
|
|
1088
|
+
/** Queue callback that delivers one terminal-submission workflow event. */
|
|
1089
|
+
const WORKFLOW_NOTIFICATION_CALLBACK = "_cfDeliverWorkflowNotification";
|
|
1090
|
+
/**
|
|
1091
|
+
* A workflow notification never retries in-process: a failed delivery
|
|
1092
|
+
* schedules its own retry with backoff (see `_cfDeliverWorkflowNotification`)
|
|
1093
|
+
* so the alarm loop is not held while a workflow is unreachable.
|
|
1094
|
+
*/
|
|
1095
|
+
const WORKFLOW_NOTIFICATION_RETRY = { maxAttempts: 1 };
|
|
1096
|
+
/** Longest wait between two delivery attempts of one workflow notification. */
|
|
1097
|
+
const WORKFLOW_NOTIFICATION_MAX_BACKOFF_SECONDS = 600;
|
|
1098
|
+
/**
|
|
1099
|
+
* How long delivery of one workflow notification keeps being retried after
|
|
1100
|
+
* its first failure. Long enough to ride out an outage of the workflow
|
|
1101
|
+
* binding; a target still failing after this is treated as permanently
|
|
1102
|
+
* unreachable rather than waking the object every ten minutes forever.
|
|
1103
|
+
*/
|
|
1104
|
+
const WORKFLOW_NOTIFICATION_GIVE_UP_MS = 720 * 60 * 1e3;
|
|
1105
|
+
/** Queue callback that runs one connection-less continuation turn. */
|
|
1106
|
+
const CONNECTIONLESS_CONTINUATION_CALLBACK = "_cfRunConnectionlessContinuation";
|
|
1107
|
+
/** Queue callback that runs one media-eviction pass. */
|
|
1108
|
+
const MEDIA_EVICTION_CALLBACK = "_cfEvictAgedMedia";
|
|
1109
|
+
/** Queue callback that runs one pending submission. */
|
|
1110
|
+
const SUBMISSION_RUN_CALLBACK = "_cfRunSubmission";
|
|
1111
|
+
function workflowNotificationItemId(submissionId, eventType) {
|
|
1112
|
+
return `workflow-notification:${submissionId}:${eventType}`;
|
|
1113
|
+
}
|
|
1114
|
+
function submissionRunItemId(submissionId) {
|
|
1115
|
+
return `submission:${submissionId}`;
|
|
1116
|
+
}
|
|
1088
1117
|
/**
|
|
1089
1118
|
* Message-metadata keys that are server-written turn context (stamped by
|
|
1090
1119
|
* `_stampChannel`) and trusted by hooks and recovery. They are stripped from
|
|
@@ -1278,7 +1307,6 @@ var Think = class Think extends Agent {
|
|
|
1278
1307
|
this.workspaceBash = true;
|
|
1279
1308
|
this.fetchTools = false;
|
|
1280
1309
|
this._mediaEvictionRunning = false;
|
|
1281
|
-
this._mediaEvictionScheduled = false;
|
|
1282
1310
|
this._mediaEvictionPending = false;
|
|
1283
1311
|
this._mediaEvictionAppendsDuringPass = 0;
|
|
1284
1312
|
this._warnedEvictionUnsupported = false;
|
|
@@ -1319,12 +1347,9 @@ var Think = class Think extends Agent {
|
|
|
1319
1347
|
this._agentToolLiveSequences = /* @__PURE__ */ new Map();
|
|
1320
1348
|
this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
|
|
1321
1349
|
this._submissionTableEnsured = false;
|
|
1322
|
-
this._workflowNotificationTableEnsured = false;
|
|
1323
1350
|
this._declaredScheduledTasksTableEnsured = false;
|
|
1324
1351
|
this._actionLedgerTableEnsured = false;
|
|
1325
1352
|
this._actionPendingTableEnsured = false;
|
|
1326
|
-
this._drainingSubmissions = false;
|
|
1327
|
-
this._drainingWorkflowNotifications = false;
|
|
1328
1353
|
this._submissionAbortControllers = /* @__PURE__ */ new Map();
|
|
1329
1354
|
this._programmaticStreamErrors = /* @__PURE__ */ new Map();
|
|
1330
1355
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
@@ -1429,10 +1454,8 @@ var Think = class Think extends Agent {
|
|
|
1429
1454
|
await withAgentSpan(this, "recover_think_durable_work", "startup", { "cloudflare.agents.component": "think" }, () => this._runBestEffortOnStartStep("durable-work-recovery", async () => {
|
|
1430
1455
|
await this._sweepActionLedger();
|
|
1431
1456
|
await this._sweepActionPendingApprovals();
|
|
1457
|
+
await this._migrateLegacyWorkflowNotifications();
|
|
1432
1458
|
await this._recoverSubmissionsOnStart();
|
|
1433
|
-
this._recoverWorkflowNotifications();
|
|
1434
|
-
if (this._hasPendingSubmissions()) await this._scheduleSubmissionDrain();
|
|
1435
|
-
if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
|
|
1436
1459
|
}, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them."));
|
|
1437
1460
|
update({
|
|
1438
1461
|
"cloudflare.agents.hydration.messages": this._lastHydration?.hydratedMessages,
|
|
@@ -1607,16 +1630,17 @@ var Think = class Think extends Agent {
|
|
|
1607
1630
|
return this._lastHydration?.truncated === true || this._cachedMessages.some((message) => isCompactionMessage(message));
|
|
1608
1631
|
}
|
|
1609
1632
|
/**
|
|
1610
|
-
*
|
|
1633
|
+
* Queue a bounded media-eviction pass (see `mediaEviction`).
|
|
1611
1634
|
*
|
|
1612
|
-
*
|
|
1613
|
-
*
|
|
1614
|
-
*
|
|
1615
|
-
*
|
|
1616
|
-
*
|
|
1635
|
+
* The pass is one queue item with a stable id, so repeated requests
|
|
1636
|
+
* coalesce and the pass runs from the alarm loop, never inside the
|
|
1637
|
+
* request or the `blockConcurrencyWhile` cache refresh that asked for it.
|
|
1638
|
+
* A request that lands while a pass is running is re-evaluated once the
|
|
1639
|
+
* pass ends, so media aged by an append during the pass is not left until
|
|
1640
|
+
* the next one. `_evictAgedMediaBestEffort` swallows its own failures, so
|
|
1641
|
+
* a bad pass can never brick the object.
|
|
1617
1642
|
*/
|
|
1618
1643
|
_scheduleMediaEvictionPass() {
|
|
1619
|
-
if (this._mediaEvictionScheduled) return;
|
|
1620
1644
|
if (this._mediaEvictionRunning) {
|
|
1621
1645
|
this._mediaEvictionPending = true;
|
|
1622
1646
|
return;
|
|
@@ -1628,11 +1652,16 @@ var Think = class Think extends Agent {
|
|
|
1628
1652
|
const fruitless = this._mediaEvictionFruitless;
|
|
1629
1653
|
if (fruitless !== null && this._lastHydration !== null && fruitless.storedBytes === this._lastHydration.totalContentBytes && fruitless.appendsSince < keepRecent) return;
|
|
1630
1654
|
} else if (!this._cachedMessages.slice(0, Math.max(0, this._cachedMessages.length - keepRecent)).some((message) => hasEvictableMedia(message, config.minPartBytes))) return;
|
|
1631
|
-
this.
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1655
|
+
this.queue(MEDIA_EVICTION_CALLBACK, void 0, { id: "media-eviction" }).catch((error) => {
|
|
1656
|
+
console.error("[Think] Failed to queue media eviction pass", error);
|
|
1657
|
+
});
|
|
1658
|
+
}
|
|
1659
|
+
/**
|
|
1660
|
+
* Run one media-eviction pass.
|
|
1661
|
+
* @internal Queue callback.
|
|
1662
|
+
*/
|
|
1663
|
+
async _cfEvictAgedMedia() {
|
|
1664
|
+
await this._evictAgedMediaBestEffort();
|
|
1636
1665
|
}
|
|
1637
1666
|
/**
|
|
1638
1667
|
* Remove aged media from the conversation, leaving a Workspace pointer the
|
|
@@ -1930,10 +1959,6 @@ var Think = class Think extends Agent {
|
|
|
1930
1959
|
WHERE run_id = ${runId}
|
|
1931
1960
|
`;
|
|
1932
1961
|
}
|
|
1933
|
-
async alarm() {
|
|
1934
|
-
await super.alarm();
|
|
1935
|
-
this._startWorkflowNotificationDrain();
|
|
1936
|
-
}
|
|
1937
1962
|
/**
|
|
1938
1963
|
* Persist an arbitrary JSON-serializable configuration object for this
|
|
1939
1964
|
* agent instance. Stored in the Think-private `think_config` table —
|
|
@@ -2477,7 +2502,12 @@ var Think = class Think extends Agent {
|
|
|
2477
2502
|
lastClientTools: this._lastClientTools
|
|
2478
2503
|
});
|
|
2479
2504
|
const wrap = (data) => wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data);
|
|
2480
|
-
|
|
2505
|
+
const acceptance = recoveredTurnAcceptanceContext.getStore();
|
|
2506
|
+
const onAccepted = acceptance?.agent === this ? acceptance.onAccepted : void 0;
|
|
2507
|
+
if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
2508
|
+
onAccepted?.(requestId);
|
|
2509
|
+
return fn();
|
|
2510
|
+
}, {
|
|
2481
2511
|
initialSnapshot: wrap(null),
|
|
2482
2512
|
wrapStash: wrap
|
|
2483
2513
|
});
|
|
@@ -2490,10 +2520,14 @@ var Think = class Think extends Agent {
|
|
|
2490
2520
|
});
|
|
2491
2521
|
outcome.catch(() => {});
|
|
2492
2522
|
const ambient = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
|
|
2523
|
+
const run = () => {
|
|
2524
|
+
onAccepted?.(requestId);
|
|
2525
|
+
return ambient ? __DO_NOT_USE_WILL_BREAK__agentContext.run(ambient, fn) : fn();
|
|
2526
|
+
};
|
|
2493
2527
|
this._liveChatTurnClosures.set(nonce, {
|
|
2494
2528
|
initial: wrap(null),
|
|
2495
2529
|
wrap,
|
|
2496
|
-
run
|
|
2530
|
+
run,
|
|
2497
2531
|
settle: {
|
|
2498
2532
|
resolve: resolveOutcome,
|
|
2499
2533
|
reject: rejectOutcome
|
|
@@ -5658,9 +5692,18 @@ var Think = class Think extends Agent {
|
|
|
5658
5692
|
created_at INTEGER NOT NULL,
|
|
5659
5693
|
messages_applied_at INTEGER,
|
|
5660
5694
|
started_at INTEGER,
|
|
5661
|
-
completed_at INTEGER
|
|
5695
|
+
completed_at INTEGER,
|
|
5696
|
+
-- Closed vocabulary: 'completed' | 'aborted' | 'retry'. NULL is legacy
|
|
5697
|
+
-- or an unsettled attempt; 'retry' is NOT terminal completion evidence.
|
|
5698
|
+
result_status TEXT,
|
|
5699
|
+
output_json TEXT
|
|
5662
5700
|
)
|
|
5663
5701
|
`;
|
|
5702
|
+
for (const statement of ["ALTER TABLE cf_think_submissions ADD COLUMN result_status TEXT", "ALTER TABLE cf_think_submissions ADD COLUMN output_json TEXT"]) try {
|
|
5703
|
+
this.ctx.storage.sql.exec(statement);
|
|
5704
|
+
} catch (error) {
|
|
5705
|
+
if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
|
|
5706
|
+
}
|
|
5664
5707
|
this.sql`
|
|
5665
5708
|
CREATE INDEX IF NOT EXISTS cf_think_submissions_status_created_idx
|
|
5666
5709
|
ON cf_think_submissions (status, created_at, submission_id)
|
|
@@ -5675,40 +5718,12 @@ var Think = class Think extends Agent {
|
|
|
5675
5718
|
`;
|
|
5676
5719
|
this._submissionTableEnsured = true;
|
|
5677
5720
|
}
|
|
5678
|
-
_ensureWorkflowNotificationTable() {
|
|
5679
|
-
if (this._workflowNotificationTableEnsured) return;
|
|
5680
|
-
this.sql`
|
|
5681
|
-
CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (
|
|
5682
|
-
notification_id TEXT PRIMARY KEY,
|
|
5683
|
-
submission_id TEXT NOT NULL,
|
|
5684
|
-
workflow_name TEXT NOT NULL,
|
|
5685
|
-
workflow_id TEXT NOT NULL,
|
|
5686
|
-
event_type TEXT NOT NULL,
|
|
5687
|
-
payload_json TEXT NOT NULL,
|
|
5688
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
5689
|
-
last_error TEXT,
|
|
5690
|
-
created_at INTEGER NOT NULL,
|
|
5691
|
-
updated_at INTEGER NOT NULL,
|
|
5692
|
-
delivered_at INTEGER
|
|
5693
|
-
)
|
|
5694
|
-
`;
|
|
5695
|
-
try {
|
|
5696
|
-
this.ctx.storage.sql.exec("ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER");
|
|
5697
|
-
} catch (error) {
|
|
5698
|
-
if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
|
|
5699
|
-
}
|
|
5700
|
-
this.sql`
|
|
5701
|
-
CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx
|
|
5702
|
-
ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)
|
|
5703
|
-
`;
|
|
5704
|
-
this._workflowNotificationTableEnsured = true;
|
|
5705
|
-
}
|
|
5706
5721
|
_readSubmission(submissionId) {
|
|
5707
5722
|
this._ensureSubmissionTable();
|
|
5708
5723
|
return this.sql`
|
|
5709
5724
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
5710
5725
|
messages_json, metadata_json, error_message, created_at,
|
|
5711
|
-
messages_applied_at, started_at, completed_at
|
|
5726
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
5712
5727
|
FROM cf_think_submissions
|
|
5713
5728
|
WHERE submission_id = ${submissionId}
|
|
5714
5729
|
LIMIT 1
|
|
@@ -5719,7 +5734,7 @@ var Think = class Think extends Agent {
|
|
|
5719
5734
|
return this.sql`
|
|
5720
5735
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
5721
5736
|
messages_json, metadata_json, error_message, created_at,
|
|
5722
|
-
messages_applied_at, started_at, completed_at
|
|
5737
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
5723
5738
|
FROM cf_think_submissions
|
|
5724
5739
|
WHERE idempotency_key = ${idempotencyKey}
|
|
5725
5740
|
LIMIT 1
|
|
@@ -5737,7 +5752,7 @@ var Think = class Think extends Agent {
|
|
|
5737
5752
|
return this.sql`
|
|
5738
5753
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
5739
5754
|
messages_json, metadata_json, error_message, created_at,
|
|
5740
|
-
messages_applied_at, started_at, completed_at
|
|
5755
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
5741
5756
|
FROM cf_think_submissions
|
|
5742
5757
|
ORDER BY created_at DESC, submission_id DESC
|
|
5743
5758
|
LIMIT ${limit}
|
|
@@ -5747,7 +5762,7 @@ var Think = class Think extends Agent {
|
|
|
5747
5762
|
return this.sql`
|
|
5748
5763
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
5749
5764
|
messages_json, metadata_json, error_message, created_at,
|
|
5750
|
-
messages_applied_at, started_at, completed_at
|
|
5765
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
5751
5766
|
FROM cf_think_submissions
|
|
5752
5767
|
WHERE status = ${status}
|
|
5753
5768
|
ORDER BY created_at DESC, submission_id DESC
|
|
@@ -5808,7 +5823,7 @@ var Think = class Think extends Agent {
|
|
|
5808
5823
|
...typeof workflowPrompt.fingerprint === "string" && { fingerprint: workflowPrompt.fingerprint }
|
|
5809
5824
|
};
|
|
5810
5825
|
}
|
|
5811
|
-
async _emitSubmissionStatus(row
|
|
5826
|
+
async _emitSubmissionStatus(row) {
|
|
5812
5827
|
const inspection = this._inspectionFromSubmissionRow(row);
|
|
5813
5828
|
this._emit("submission:status", {
|
|
5814
5829
|
submissionId: inspection.submissionId,
|
|
@@ -5829,7 +5844,6 @@ var Think = class Think extends Agent {
|
|
|
5829
5844
|
error: inspection.error
|
|
5830
5845
|
});
|
|
5831
5846
|
}
|
|
5832
|
-
if (this._isTerminalSubmissionStatus(inspection.status)) await this._enqueueWorkflowNotification(inspection, output);
|
|
5833
5847
|
await this.keepAliveWhile(async () => {
|
|
5834
5848
|
try {
|
|
5835
5849
|
await this.onSubmissionStatus(inspection);
|
|
@@ -5839,171 +5853,112 @@ var Think = class Think extends Agent {
|
|
|
5839
5853
|
});
|
|
5840
5854
|
}
|
|
5841
5855
|
onSubmissionStatus(_submission) {}
|
|
5842
|
-
|
|
5843
|
-
|
|
5844
|
-
|
|
5845
|
-
|
|
5846
|
-
|
|
5856
|
+
/**
|
|
5857
|
+
* Queue the workflow event for a submission that just went terminal.
|
|
5858
|
+
*
|
|
5859
|
+
* The item is written synchronously (the Lifecycle has started whenever a
|
|
5860
|
+
* submission transitions), so call this in the same synchronous block as
|
|
5861
|
+
* the terminal status write: the two commit together and no recovery scan
|
|
5862
|
+
* is needed. A repeated push for the same submission and event type
|
|
5863
|
+
* replaces the pending item rather than duplicating it.
|
|
5864
|
+
*/
|
|
5865
|
+
_insertWorkflowNotification(submission, output) {
|
|
5847
5866
|
const workflowPrompt = this._readWorkflowPromptContext(submission.metadata ?? null);
|
|
5848
5867
|
if (!workflowPrompt) return false;
|
|
5849
|
-
|
|
5850
|
-
const now = Date.now();
|
|
5851
|
-
const status = override?.status ?? submission.status;
|
|
5852
|
-
const error = override?.error ?? submission.error;
|
|
5868
|
+
const { status, error } = submission;
|
|
5853
5869
|
const payload = {
|
|
5854
5870
|
submissionId: submission.submissionId,
|
|
5855
5871
|
status,
|
|
5856
5872
|
...status === "completed" && { output },
|
|
5857
5873
|
...error && { error }
|
|
5858
5874
|
};
|
|
5859
|
-
this.
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
0,
|
|
5872
|
-
NULL,
|
|
5873
|
-
${now},
|
|
5874
|
-
${now},
|
|
5875
|
-
NULL
|
|
5876
|
-
)
|
|
5877
|
-
`;
|
|
5878
|
-
return true;
|
|
5879
|
-
}
|
|
5880
|
-
_recoverWorkflowNotifications() {
|
|
5881
|
-
this._ensureSubmissionTable();
|
|
5882
|
-
this._ensureWorkflowNotificationTable();
|
|
5883
|
-
const terminalRows = this.sql`
|
|
5884
|
-
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
5885
|
-
messages_json, metadata_json, error_message, created_at,
|
|
5886
|
-
messages_applied_at, started_at, completed_at
|
|
5887
|
-
FROM cf_think_submissions
|
|
5888
|
-
WHERE status IN ('aborted', 'skipped', 'error')
|
|
5889
|
-
ORDER BY completed_at DESC, created_at DESC
|
|
5890
|
-
LIMIT 100
|
|
5891
|
-
`;
|
|
5892
|
-
let recovered = false;
|
|
5893
|
-
for (const row of terminalRows) {
|
|
5894
|
-
const inspection = this._inspectionFromSubmissionRow(row);
|
|
5895
|
-
const workflowPrompt = this._readWorkflowPromptContext(inspection.metadata ?? null);
|
|
5896
|
-
if (!workflowPrompt) continue;
|
|
5897
|
-
const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;
|
|
5898
|
-
if (this.sql`
|
|
5899
|
-
SELECT notification_id
|
|
5900
|
-
FROM cf_think_workflow_notifications
|
|
5901
|
-
WHERE notification_id = ${notificationId}
|
|
5902
|
-
LIMIT 1
|
|
5903
|
-
`[0]) continue;
|
|
5904
|
-
recovered = this._insertWorkflowNotification(inspection) || recovered;
|
|
5905
|
-
}
|
|
5906
|
-
if (recovered) this._startWorkflowNotificationDrain();
|
|
5907
|
-
}
|
|
5908
|
-
_startWorkflowNotificationDrain() {
|
|
5909
|
-
if (!this._hasPendingWorkflowNotifications()) return;
|
|
5910
|
-
this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch((error) => {
|
|
5911
|
-
console.error("[Think] Failed to drain workflow notifications", error);
|
|
5912
|
-
this._rearmWorkflowNotificationAlarm();
|
|
5875
|
+
this.queue(WORKFLOW_NOTIFICATION_CALLBACK, {
|
|
5876
|
+
workflowName: workflowPrompt.workflow.name,
|
|
5877
|
+
workflowId: workflowPrompt.workflow.id,
|
|
5878
|
+
event: {
|
|
5879
|
+
type: workflowPrompt.workflow.eventType,
|
|
5880
|
+
payload
|
|
5881
|
+
}
|
|
5882
|
+
}, {
|
|
5883
|
+
id: workflowNotificationItemId(submission.submissionId, workflowPrompt.workflow.eventType),
|
|
5884
|
+
retry: WORKFLOW_NOTIFICATION_RETRY
|
|
5885
|
+
}).catch((error) => {
|
|
5886
|
+
console.error("[Think] Failed to queue workflow notification", error);
|
|
5913
5887
|
});
|
|
5888
|
+
return true;
|
|
5914
5889
|
}
|
|
5915
|
-
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
FROM cf_think_workflow_notifications
|
|
5920
|
-
WHERE delivered_at IS NULL
|
|
5921
|
-
LIMIT 1
|
|
5922
|
-
`.length > 0;
|
|
5890
|
+
/** Queue the workflow event for a row that a caller just made terminal. */
|
|
5891
|
+
_enqueueTerminalWorkflowNotification(row, output) {
|
|
5892
|
+
if (!row || !this._isTerminalSubmissionStatus(row.status)) return;
|
|
5893
|
+
this._insertWorkflowNotification(this._inspectionFromSubmissionRow(row), output);
|
|
5923
5894
|
}
|
|
5924
|
-
|
|
5925
|
-
|
|
5926
|
-
|
|
5927
|
-
|
|
5895
|
+
/**
|
|
5896
|
+
* Deliver one workflow notification. Runs from the queue on first
|
|
5897
|
+
* delivery; a failed delivery schedules this same callback again with
|
|
5898
|
+
* exponential backoff (2s doubling, capped at ten minutes) so a
|
|
5899
|
+
* temporarily unreachable workflow still gets its terminal event. Once
|
|
5900
|
+
* the first failure is twelve hours old delivery gives up by throwing:
|
|
5901
|
+
* the dispatching capability reports it through its error event and the
|
|
5902
|
+
* Agent's `onError`.
|
|
5903
|
+
* @internal Queue and schedule callback.
|
|
5904
|
+
*/
|
|
5905
|
+
async _cfDeliverWorkflowNotification(payload) {
|
|
5928
5906
|
try {
|
|
5929
|
-
|
|
5930
|
-
|
|
5931
|
-
|
|
5932
|
-
|
|
5933
|
-
|
|
5934
|
-
|
|
5935
|
-
|
|
5936
|
-
|
|
5937
|
-
`;
|
|
5938
|
-
for (const row of rows) try {
|
|
5939
|
-
const payload = JSON.parse(row.payload_json);
|
|
5940
|
-
await this.sendWorkflowEvent(row.workflow_name, row.workflow_id, {
|
|
5941
|
-
type: row.event_type,
|
|
5942
|
-
payload
|
|
5943
|
-
});
|
|
5944
|
-
this.sql`
|
|
5945
|
-
UPDATE cf_think_workflow_notifications
|
|
5946
|
-
SET payload_json = '{}',
|
|
5947
|
-
last_error = NULL,
|
|
5948
|
-
updated_at = ${Date.now()},
|
|
5949
|
-
delivered_at = ${Date.now()}
|
|
5950
|
-
WHERE notification_id = ${row.notification_id}
|
|
5951
|
-
AND delivered_at IS NULL
|
|
5952
|
-
`;
|
|
5953
|
-
} catch (error) {
|
|
5954
|
-
this.sql`
|
|
5955
|
-
UPDATE cf_think_workflow_notifications
|
|
5956
|
-
SET attempts = attempts + 1,
|
|
5957
|
-
last_error = ${error instanceof Error ? error.message : String(error)},
|
|
5958
|
-
updated_at = ${Date.now()}
|
|
5959
|
-
WHERE notification_id = ${row.notification_id}
|
|
5960
|
-
`;
|
|
5907
|
+
await this.sendWorkflowEvent(payload.workflowName, payload.workflowId, payload.event);
|
|
5908
|
+
} catch (error) {
|
|
5909
|
+
const attempts = (payload.attempts ?? 0) + 1;
|
|
5910
|
+
const firstFailedAt = payload.firstFailedAt ?? Date.now();
|
|
5911
|
+
if (Date.now() - firstFailedAt >= WORKFLOW_NOTIFICATION_GIVE_UP_MS) {
|
|
5912
|
+
const summary = `Workflow notification for submission ${JSON.stringify(payload.event.payload?.submissionId)} (${payload.workflowName}/${payload.workflowId}, ${payload.event.type}) could not be delivered after ${attempts} attempts over 12h; giving up`;
|
|
5913
|
+
console.error(`[Think] ${summary}`, error);
|
|
5914
|
+
throw new Error(summary);
|
|
5961
5915
|
}
|
|
5962
|
-
|
|
5963
|
-
|
|
5916
|
+
const delaySeconds = Math.min(WORKFLOW_NOTIFICATION_MAX_BACKOFF_SECONDS, 2 ** Math.min(attempts, 20));
|
|
5917
|
+
console.error(`[Think] Workflow notification delivery failed (attempt ${attempts}); retrying in ${delaySeconds}s`, error);
|
|
5918
|
+
await this.schedule(delaySeconds, WORKFLOW_NOTIFICATION_CALLBACK, {
|
|
5919
|
+
...payload,
|
|
5920
|
+
attempts,
|
|
5921
|
+
firstFailedAt
|
|
5922
|
+
});
|
|
5964
5923
|
}
|
|
5965
|
-
await this._rearmWorkflowNotificationAlarm();
|
|
5966
5924
|
}
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
5925
|
+
/**
|
|
5926
|
+
* Move undelivered rows of the retired `cf_think_workflow_notifications`
|
|
5927
|
+
* outbox into the queue and drop the table. Idempotent: a missing table
|
|
5928
|
+
* means a fresh object or a completed migration.
|
|
5929
|
+
*
|
|
5930
|
+
* TEMPORARY: one-shot upgrade path for objects that were mid-delivery when
|
|
5931
|
+
* this release landed. Remove in the next minor release, once every
|
|
5932
|
+
* deployed object has started on this version and migrated.
|
|
5933
|
+
*/
|
|
5934
|
+
async _migrateLegacyWorkflowNotifications() {
|
|
5935
|
+
if (this.ctx.storage.sql.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='cf_think_workflow_notifications'").toArray().length === 0) return;
|
|
5936
|
+
const rows = this.sql`
|
|
5937
|
+
SELECT submission_id, workflow_name, workflow_id, event_type, payload_json
|
|
5971
5938
|
FROM cf_think_workflow_notifications
|
|
5972
5939
|
WHERE delivered_at IS NULL
|
|
5973
5940
|
ORDER BY created_at ASC, notification_id ASC
|
|
5974
|
-
LIMIT 1
|
|
5975
5941
|
`;
|
|
5976
|
-
|
|
5977
|
-
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
|
|
5981
|
-
|
|
5982
|
-
|
|
5983
|
-
|
|
5984
|
-
|
|
5985
|
-
|
|
5986
|
-
|
|
5987
|
-
|
|
5988
|
-
|
|
5989
|
-
|
|
5990
|
-
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
* Replaces the pull-based `_getExtensionAlarm()` contribution.
|
|
5995
|
-
*/
|
|
5996
|
-
async _rearmWorkflowNotificationAlarm() {
|
|
5997
|
-
const next = this._nextWorkflowNotificationAlarm();
|
|
5998
|
-
if (next === null) {
|
|
5999
|
-
if (this.lifecycle.jobs.get(THINK_WORKFLOW_NOTIFICATIONS_JOB_ID)) await this.lifecycle.jobs.cancel(THINK_WORKFLOW_NOTIFICATIONS_JOB_ID);
|
|
6000
|
-
return;
|
|
5942
|
+
for (const row of rows) {
|
|
5943
|
+
let payload;
|
|
5944
|
+
try {
|
|
5945
|
+
payload = JSON.parse(row.payload_json);
|
|
5946
|
+
} catch {
|
|
5947
|
+
continue;
|
|
5948
|
+
}
|
|
5949
|
+
await this.queue(WORKFLOW_NOTIFICATION_CALLBACK, {
|
|
5950
|
+
workflowName: row.workflow_name,
|
|
5951
|
+
workflowId: row.workflow_id,
|
|
5952
|
+
event: {
|
|
5953
|
+
type: row.event_type,
|
|
5954
|
+
payload
|
|
5955
|
+
}
|
|
5956
|
+
}, {
|
|
5957
|
+
id: workflowNotificationItemId(row.submission_id, row.event_type),
|
|
5958
|
+
retry: WORKFLOW_NOTIFICATION_RETRY
|
|
5959
|
+
});
|
|
6001
5960
|
}
|
|
6002
|
-
|
|
6003
|
-
id: THINK_WORKFLOW_NOTIFICATIONS_JOB_ID,
|
|
6004
|
-
fn: "thinkWorkflowNotifications",
|
|
6005
|
-
time: next
|
|
6006
|
-
});
|
|
5961
|
+
this.sql`DROP TABLE cf_think_workflow_notifications`;
|
|
6007
5962
|
}
|
|
6008
5963
|
async inspectSubmission(submissionId) {
|
|
6009
5964
|
const row = this._readSubmission(submissionId);
|
|
@@ -6046,7 +6001,7 @@ var Think = class Think extends Agent {
|
|
|
6046
6001
|
if (completedBefore === void 0) return this.sql`
|
|
6047
6002
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
6048
6003
|
messages_json, metadata_json, error_message, created_at,
|
|
6049
|
-
messages_applied_at, started_at, completed_at
|
|
6004
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
6050
6005
|
FROM cf_think_submissions
|
|
6051
6006
|
WHERE status = ${status}
|
|
6052
6007
|
ORDER BY completed_at ASC, created_at ASC
|
|
@@ -6055,7 +6010,7 @@ var Think = class Think extends Agent {
|
|
|
6055
6010
|
return this.sql`
|
|
6056
6011
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
6057
6012
|
messages_json, metadata_json, error_message, created_at,
|
|
6058
|
-
messages_applied_at, started_at, completed_at
|
|
6013
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
6059
6014
|
FROM cf_think_submissions
|
|
6060
6015
|
WHERE status = ${status}
|
|
6061
6016
|
AND completed_at IS NOT NULL
|
|
@@ -6078,12 +6033,18 @@ var Think = class Think extends Agent {
|
|
|
6078
6033
|
UPDATE cf_think_submissions
|
|
6079
6034
|
SET status = 'aborted',
|
|
6080
6035
|
error_message = ${errorMessage},
|
|
6081
|
-
completed_at = ${completedAt}
|
|
6036
|
+
completed_at = ${completedAt},
|
|
6037
|
+
result_status = NULL,
|
|
6038
|
+
output_json = NULL
|
|
6082
6039
|
WHERE submission_id = ${submissionId}
|
|
6083
6040
|
AND status IN ('pending', 'running')
|
|
6084
6041
|
`;
|
|
6085
6042
|
const updated = this._readSubmission(submissionId);
|
|
6086
|
-
if (updated?.status === "aborted")
|
|
6043
|
+
if (updated?.status === "aborted") {
|
|
6044
|
+
this._enqueueTerminalWorkflowNotification(updated);
|
|
6045
|
+
await this.dequeue(submissionRunItemId(submissionId));
|
|
6046
|
+
await this._emitSubmissionStatus(updated);
|
|
6047
|
+
}
|
|
6087
6048
|
}
|
|
6088
6049
|
async submitMessages(messages, options) {
|
|
6089
6050
|
messages = this._stampChannel(messages, options?.channel);
|
|
@@ -6100,7 +6061,7 @@ var Think = class Think extends Agent {
|
|
|
6100
6061
|
if (existingById && options?.idempotencyKey && existingById.idempotency_key !== null && existingById.idempotency_key !== options.idempotencyKey) throw new Error("submissionId and idempotencyKey refer to different submissions");
|
|
6101
6062
|
const existing = existingById ?? existingByKey;
|
|
6102
6063
|
if (existing) {
|
|
6103
|
-
if (existing.status === "pending") await this.
|
|
6064
|
+
if (existing.status === "pending") await this._queueSubmissionRun(existing.submission_id);
|
|
6104
6065
|
return {
|
|
6105
6066
|
...this._inspectionFromSubmissionRow(existing),
|
|
6106
6067
|
accepted: false
|
|
@@ -6131,7 +6092,7 @@ var Think = class Think extends Agent {
|
|
|
6131
6092
|
idempotencyKey: row.idempotency_key ?? void 0
|
|
6132
6093
|
});
|
|
6133
6094
|
await this._emitSubmissionStatus(row);
|
|
6134
|
-
await this.
|
|
6095
|
+
await this._queueSubmissionRun(submissionId);
|
|
6135
6096
|
return {
|
|
6136
6097
|
...this._inspectionFromSubmissionRow(row),
|
|
6137
6098
|
accepted: true
|
|
@@ -6139,44 +6100,36 @@ var Think = class Think extends Agent {
|
|
|
6139
6100
|
}
|
|
6140
6101
|
});
|
|
6141
6102
|
}
|
|
6142
|
-
|
|
6143
|
-
|
|
6103
|
+
/**
|
|
6104
|
+
* Queue the run of one pending submission. Idempotent: the stable id
|
|
6105
|
+
* replaces an item already queued for the submission in place, keeping
|
|
6106
|
+
* its FIFO slot, and re-arms the physical alarm so a lost alarm recovers.
|
|
6107
|
+
*/
|
|
6108
|
+
async _queueSubmissionRun(submissionId) {
|
|
6109
|
+
await this.queue(SUBMISSION_RUN_CALLBACK, { submissionId }, { id: submissionRunItemId(submissionId) });
|
|
6144
6110
|
}
|
|
6145
|
-
|
|
6111
|
+
/** Queue a run for every pending submission that has none. */
|
|
6112
|
+
async _queuePendingSubmissionRuns() {
|
|
6146
6113
|
this._ensureSubmissionTable();
|
|
6147
|
-
|
|
6114
|
+
const pending = this.sql`
|
|
6148
6115
|
SELECT submission_id
|
|
6149
6116
|
FROM cf_think_submissions
|
|
6150
6117
|
WHERE status = 'pending'
|
|
6151
|
-
|
|
6152
|
-
|
|
6153
|
-
|
|
6154
|
-
async _drainThinkSubmissions() {
|
|
6155
|
-
await this._drainSubmissions();
|
|
6118
|
+
ORDER BY created_at ASC, submission_id ASC
|
|
6119
|
+
`;
|
|
6120
|
+
for (const row of pending) await this._queueSubmissionRun(row.submission_id);
|
|
6156
6121
|
}
|
|
6157
|
-
|
|
6122
|
+
/**
|
|
6123
|
+
* Run one pending submission. Runs on the Lifecycle alarm loop through the
|
|
6124
|
+
* Queue capability, one item at a time in submission order; a row that is
|
|
6125
|
+
* no longer pending (cancelled, skipped, or claimed by an overlapping
|
|
6126
|
+
* dispatch) is a no-op.
|
|
6127
|
+
* @internal Queue callback.
|
|
6128
|
+
*/
|
|
6129
|
+
async _cfRunSubmission(payload) {
|
|
6158
6130
|
this._ensureSubmissionTable();
|
|
6159
|
-
|
|
6160
|
-
|
|
6161
|
-
try {
|
|
6162
|
-
while (true) {
|
|
6163
|
-
const row = this.sql`
|
|
6164
|
-
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
6165
|
-
messages_json, metadata_json, error_message, created_at,
|
|
6166
|
-
messages_applied_at, started_at, completed_at
|
|
6167
|
-
FROM cf_think_submissions
|
|
6168
|
-
WHERE status = 'pending'
|
|
6169
|
-
ORDER BY created_at ASC, submission_id ASC
|
|
6170
|
-
LIMIT 1
|
|
6171
|
-
`[0];
|
|
6172
|
-
if (!row) break;
|
|
6173
|
-
await this._runSubmission(row);
|
|
6174
|
-
}
|
|
6175
|
-
} finally {
|
|
6176
|
-
this._drainingSubmissions = false;
|
|
6177
|
-
}
|
|
6178
|
-
}
|
|
6179
|
-
async _runSubmission(row) {
|
|
6131
|
+
const row = this._readSubmission(payload.submissionId);
|
|
6132
|
+
if (!row || row.status !== "pending") return;
|
|
6180
6133
|
await this._admitTurn({
|
|
6181
6134
|
admission: "execute-submission",
|
|
6182
6135
|
trigger: "submission",
|
|
@@ -6235,7 +6188,9 @@ var Think = class Think extends Agent {
|
|
|
6235
6188
|
request_id = ${result.requestId},
|
|
6236
6189
|
stream_id = ${streamId},
|
|
6237
6190
|
error_message = ${finalStatus === "error" ? errorMessage : null},
|
|
6238
|
-
completed_at = ${completedAt}
|
|
6191
|
+
completed_at = ${completedAt},
|
|
6192
|
+
result_status = NULL,
|
|
6193
|
+
output_json = NULL
|
|
6239
6194
|
WHERE submission_id = ${row.submission_id}
|
|
6240
6195
|
AND status = 'running'
|
|
6241
6196
|
`;
|
|
@@ -6250,7 +6205,9 @@ var Think = class Think extends Agent {
|
|
|
6250
6205
|
UPDATE cf_think_submissions
|
|
6251
6206
|
SET status = 'error',
|
|
6252
6207
|
error_message = ${errorMessage},
|
|
6253
|
-
completed_at = ${completedAt}
|
|
6208
|
+
completed_at = ${completedAt},
|
|
6209
|
+
result_status = NULL,
|
|
6210
|
+
output_json = NULL
|
|
6254
6211
|
WHERE submission_id = ${row.submission_id}
|
|
6255
6212
|
AND status = 'running'
|
|
6256
6213
|
`;
|
|
@@ -6261,7 +6218,7 @@ var Think = class Think extends Agent {
|
|
|
6261
6218
|
this._programmaticStreamErrors.delete(requestId);
|
|
6262
6219
|
this._submissionAbortControllers.delete(row.submission_id);
|
|
6263
6220
|
const updated = this._readSubmission(row.submission_id);
|
|
6264
|
-
if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated
|
|
6221
|
+
if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
|
|
6265
6222
|
}
|
|
6266
6223
|
}
|
|
6267
6224
|
_getSubmissionFinalStatus(resultStatus, streamError) {
|
|
@@ -6272,7 +6229,7 @@ var Think = class Think extends Agent {
|
|
|
6272
6229
|
const pending = this.sql`
|
|
6273
6230
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
6274
6231
|
messages_json, metadata_json, error_message, created_at,
|
|
6275
|
-
messages_applied_at, started_at, completed_at
|
|
6232
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
6276
6233
|
FROM cf_think_submissions
|
|
6277
6234
|
WHERE status = 'pending'
|
|
6278
6235
|
`;
|
|
@@ -6283,6 +6240,12 @@ var Think = class Think extends Agent {
|
|
|
6283
6240
|
completed_at = ${Date.now()}
|
|
6284
6241
|
WHERE status = 'pending'
|
|
6285
6242
|
`;
|
|
6243
|
+
for (const row of pending) {
|
|
6244
|
+
this._enqueueTerminalWorkflowNotification(this._readSubmission(row.submission_id));
|
|
6245
|
+
this.dequeue(submissionRunItemId(row.submission_id)).catch((error) => {
|
|
6246
|
+
console.error("[Think] Failed to dequeue skipped submission", error);
|
|
6247
|
+
});
|
|
6248
|
+
}
|
|
6286
6249
|
return pending;
|
|
6287
6250
|
}
|
|
6288
6251
|
async _emitSkippedSubmissions(skipped) {
|
|
@@ -6296,11 +6259,15 @@ var Think = class Think extends Agent {
|
|
|
6296
6259
|
const running = this.sql`
|
|
6297
6260
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
6298
6261
|
messages_json, metadata_json, error_message, created_at,
|
|
6299
|
-
messages_applied_at, started_at, completed_at
|
|
6262
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
6300
6263
|
FROM cf_think_submissions
|
|
6301
6264
|
WHERE status = 'running'
|
|
6302
6265
|
`;
|
|
6303
6266
|
for (const row of running) {
|
|
6267
|
+
if (row.result_status === "completed" || row.result_status === "aborted") {
|
|
6268
|
+
await this._completeRecoveredSubmission(row, row.result_status, row.request_id, null);
|
|
6269
|
+
continue;
|
|
6270
|
+
}
|
|
6304
6271
|
if (row.messages_applied_at === null) {
|
|
6305
6272
|
let appliedState;
|
|
6306
6273
|
try {
|
|
@@ -6315,7 +6282,10 @@ var Think = class Think extends Agent {
|
|
|
6315
6282
|
AND status = 'running'
|
|
6316
6283
|
`;
|
|
6317
6284
|
const updated = this._readSubmission(row.submission_id);
|
|
6318
|
-
if (updated?.status === "error")
|
|
6285
|
+
if (updated?.status === "error") {
|
|
6286
|
+
this._enqueueTerminalWorkflowNotification(updated);
|
|
6287
|
+
await this._emitSubmissionStatus(updated);
|
|
6288
|
+
}
|
|
6319
6289
|
continue;
|
|
6320
6290
|
}
|
|
6321
6291
|
if (appliedState !== "none") {
|
|
@@ -6328,7 +6298,10 @@ var Think = class Think extends Agent {
|
|
|
6328
6298
|
AND status = 'running'
|
|
6329
6299
|
`;
|
|
6330
6300
|
const updated = this._readSubmission(row.submission_id);
|
|
6331
|
-
if (updated?.status === "error")
|
|
6301
|
+
if (updated?.status === "error") {
|
|
6302
|
+
this._enqueueTerminalWorkflowNotification(updated);
|
|
6303
|
+
await this._emitSubmissionStatus(updated);
|
|
6304
|
+
}
|
|
6332
6305
|
continue;
|
|
6333
6306
|
}
|
|
6334
6307
|
this.sql`
|
|
@@ -6342,7 +6315,13 @@ var Think = class Think extends Agent {
|
|
|
6342
6315
|
if (updated?.status === "pending") await this._emitSubmissionStatus(updated);
|
|
6343
6316
|
continue;
|
|
6344
6317
|
}
|
|
6345
|
-
if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || await this.
|
|
6318
|
+
if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || await this._hasScheduledChatRecovery(row))) continue;
|
|
6319
|
+
const terminalStream = row.request_id ? this._resumableStream.latestStreamInfoForRequest(row.request_id) : null;
|
|
6320
|
+
const errored = row.result_status === "error" || terminalStream?.status === "error";
|
|
6321
|
+
if (errored || terminalStream?.status === "completed" && row.result_status !== "retry") {
|
|
6322
|
+
await this._completeRecoveredSubmission(row, errored ? "error" : "completed", row.request_id, errored ? "Recovered chat stream had already errored." : null);
|
|
6323
|
+
continue;
|
|
6324
|
+
}
|
|
6346
6325
|
this.sql`
|
|
6347
6326
|
UPDATE cf_think_submissions
|
|
6348
6327
|
SET status = 'error',
|
|
@@ -6352,8 +6331,12 @@ var Think = class Think extends Agent {
|
|
|
6352
6331
|
AND status = 'running'
|
|
6353
6332
|
`;
|
|
6354
6333
|
const updated = this._readSubmission(row.submission_id);
|
|
6355
|
-
if (updated?.status === "error")
|
|
6334
|
+
if (updated?.status === "error") {
|
|
6335
|
+
this._enqueueTerminalWorkflowNotification(updated);
|
|
6336
|
+
await this._emitSubmissionStatus(updated);
|
|
6337
|
+
}
|
|
6356
6338
|
}
|
|
6339
|
+
await this._queuePendingSubmissionRuns();
|
|
6357
6340
|
}
|
|
6358
6341
|
async _getSubmissionMessagesAppliedState(row) {
|
|
6359
6342
|
const messages = this._parseSubmissionMessages(row.messages_json);
|
|
@@ -6400,7 +6383,9 @@ var Think = class Think extends Agent {
|
|
|
6400
6383
|
const streamInfo = this._resumableStream.latestActiveStreamInfoForRequest(row.request_id);
|
|
6401
6384
|
return streamInfo ? streamInfo.createdAt >= cutoff : false;
|
|
6402
6385
|
}
|
|
6403
|
-
async
|
|
6386
|
+
async _hasScheduledChatRecovery(submission) {
|
|
6387
|
+
const isChatRecoveryCallback = (callback) => callback === "_chatRecoveryContinue" || callback === "_chatRecoveryRetry";
|
|
6388
|
+
const matchesSubmission = (recoveredRequestId) => typeof recoveredRequestId === "string" && this._readRunningSubmissionForRecovery(recoveredRequestId)?.submission_id === submission.submission_id;
|
|
6404
6389
|
if ((await this.tasks.list({
|
|
6405
6390
|
definition: CHAT_RECOVERY_TASK_NAME,
|
|
6406
6391
|
status: [
|
|
@@ -6409,11 +6394,11 @@ var Think = class Think extends Agent {
|
|
|
6409
6394
|
"waiting"
|
|
6410
6395
|
],
|
|
6411
6396
|
limit: Number.MAX_SAFE_INTEGER
|
|
6412
|
-
})).some((run) => run.metadata?.callback
|
|
6397
|
+
})).some((run) => isChatRecoveryCallback(run.metadata?.callback) && matchesSubmission(run.metadata.recoveredRequestId))) return true;
|
|
6413
6398
|
return (await this.listSchedules()).some((schedule) => {
|
|
6414
|
-
if (schedule.callback
|
|
6399
|
+
if (!isChatRecoveryCallback(schedule.callback)) return false;
|
|
6415
6400
|
const payload = schedule.payload;
|
|
6416
|
-
return payload !== null && typeof payload === "object" && "recoveredRequestId" in payload && payload.recoveredRequestId
|
|
6401
|
+
return payload !== null && typeof payload === "object" && "recoveredRequestId" in payload && matchesSubmission(payload.recoveredRequestId);
|
|
6417
6402
|
});
|
|
6418
6403
|
}
|
|
6419
6404
|
/**
|
|
@@ -7343,14 +7328,14 @@ var Think = class Think extends Agent {
|
|
|
7343
7328
|
if (!streamDrainedNaturally) this._drainInferenceStream(result);
|
|
7344
7329
|
}
|
|
7345
7330
|
if (overflowRetry) {
|
|
7346
|
-
this.
|
|
7331
|
+
this._completeSubmissionRetryStream(streamId, requestId);
|
|
7347
7332
|
streamFinalized = true;
|
|
7348
7333
|
return {
|
|
7349
7334
|
status: "overflow_retry",
|
|
7350
7335
|
error: streamError
|
|
7351
7336
|
};
|
|
7352
7337
|
}
|
|
7353
|
-
if (streamError) this._errorResumableStream(streamId);
|
|
7338
|
+
if (streamError) this._errorResumableStream(streamId, requestId);
|
|
7354
7339
|
else this._finishResumableStream(streamId);
|
|
7355
7340
|
streamFinalized = true;
|
|
7356
7341
|
this._broadcastChat({
|
|
@@ -7362,10 +7347,13 @@ var Think = class Think extends Agent {
|
|
|
7362
7347
|
doneSent = true;
|
|
7363
7348
|
assistantMsg = accumulator.toMessage();
|
|
7364
7349
|
if (accumulator.parts.length > 0) {
|
|
7365
|
-
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, void 0,
|
|
7350
|
+
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, void 0, this._streamCutoverOptions(requestId), {
|
|
7351
|
+
requestId,
|
|
7352
|
+
result: { status: aborted ? "aborted" : "completed" }
|
|
7353
|
+
});
|
|
7366
7354
|
this._broadcastMessages();
|
|
7367
7355
|
}
|
|
7368
|
-
this.
|
|
7356
|
+
this._finalizeSubmissionStream(requestId, { status: aborted ? "aborted" : "completed" });
|
|
7369
7357
|
if (streamError) {
|
|
7370
7358
|
await this._fireResponseHook({
|
|
7371
7359
|
message: assistantMsg,
|
|
@@ -7422,7 +7410,7 @@ var Think = class Think extends Agent {
|
|
|
7422
7410
|
}
|
|
7423
7411
|
if (outcome === "exhausted") {
|
|
7424
7412
|
if (!streamFinalized) {
|
|
7425
|
-
this._errorResumableStream(streamId);
|
|
7413
|
+
this._errorResumableStream(streamId, requestId);
|
|
7426
7414
|
streamFinalized = true;
|
|
7427
7415
|
}
|
|
7428
7416
|
doneSent = true;
|
|
@@ -7432,7 +7420,7 @@ var Think = class Think extends Agent {
|
|
|
7432
7420
|
}
|
|
7433
7421
|
}
|
|
7434
7422
|
if (!streamFinalized) {
|
|
7435
|
-
this._errorResumableStream(streamId);
|
|
7423
|
+
this._errorResumableStream(streamId, requestId);
|
|
7436
7424
|
streamFinalized = true;
|
|
7437
7425
|
}
|
|
7438
7426
|
if (!doneSent) {
|
|
@@ -7593,14 +7581,14 @@ var Think = class Think extends Agent {
|
|
|
7593
7581
|
if (!streamDrainedNaturally) this._drainInferenceStream(result);
|
|
7594
7582
|
}
|
|
7595
7583
|
if (overflowRetry && options?.overflowRecovery) {
|
|
7596
|
-
this.
|
|
7584
|
+
this._completeSubmissionRetryStream(streamId, requestId);
|
|
7597
7585
|
this._pendingResumeConnections.clear();
|
|
7598
7586
|
doneSent = true;
|
|
7599
7587
|
options.overflowRecovery.onRetry(streamError);
|
|
7600
7588
|
this._streamingAssistant = null;
|
|
7601
7589
|
return { status: "aborted" };
|
|
7602
7590
|
}
|
|
7603
|
-
if (streamError) this._errorResumableStream(streamId);
|
|
7591
|
+
if (streamError) this._errorResumableStream(streamId, requestId);
|
|
7604
7592
|
else this._finishResumableStream(streamId);
|
|
7605
7593
|
this._pendingResumeConnections.clear();
|
|
7606
7594
|
this._broadcastChat({
|
|
@@ -7643,7 +7631,7 @@ var Think = class Think extends Agent {
|
|
|
7643
7631
|
return { status: "aborted" };
|
|
7644
7632
|
}
|
|
7645
7633
|
if (outcome === "exhausted") {
|
|
7646
|
-
this._errorResumableStream(streamId);
|
|
7634
|
+
this._errorResumableStream(streamId, requestId);
|
|
7647
7635
|
this._pendingResumeConnections.clear();
|
|
7648
7636
|
doneSent = true;
|
|
7649
7637
|
this._streamingAssistant = null;
|
|
@@ -7652,7 +7640,7 @@ var Think = class Think extends Agent {
|
|
|
7652
7640
|
}
|
|
7653
7641
|
streamError = error instanceof Error ? error.message : "Stream error";
|
|
7654
7642
|
if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
|
|
7655
|
-
this._errorResumableStream(streamId);
|
|
7643
|
+
this._errorResumableStream(streamId, requestId);
|
|
7656
7644
|
this._pendingResumeConnections.clear();
|
|
7657
7645
|
if (!doneSent) {
|
|
7658
7646
|
this._broadcastChat({
|
|
@@ -7667,7 +7655,7 @@ var Think = class Think extends Agent {
|
|
|
7667
7655
|
}
|
|
7668
7656
|
} finally {
|
|
7669
7657
|
if (!doneSent) {
|
|
7670
|
-
this._errorResumableStream(streamId);
|
|
7658
|
+
this._errorResumableStream(streamId, requestId);
|
|
7671
7659
|
this._pendingResumeConnections.clear();
|
|
7672
7660
|
this._broadcastChat({
|
|
7673
7661
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -7683,14 +7671,22 @@ var Think = class Think extends Agent {
|
|
|
7683
7671
|
} catch (error) {
|
|
7684
7672
|
streamError = error instanceof Error ? error.message : "Structured output error";
|
|
7685
7673
|
if (options.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
|
|
7674
|
+
this._errorResumableStream(streamId, requestId);
|
|
7686
7675
|
}
|
|
7676
|
+
const submissionResult = streamAborted ? { status: "aborted" } : {
|
|
7677
|
+
status: "completed",
|
|
7678
|
+
output
|
|
7679
|
+
};
|
|
7687
7680
|
if (this._turnQueue.generation === clearGen) try {
|
|
7688
7681
|
const assistantMsg = accumulator.toMessage();
|
|
7689
7682
|
if (accumulator.parts.length > 0) {
|
|
7690
|
-
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, parentId,
|
|
7683
|
+
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, parentId, this._streamCutoverOptions(requestId), {
|
|
7684
|
+
requestId,
|
|
7685
|
+
result: submissionResult
|
|
7686
|
+
});
|
|
7691
7687
|
this._broadcastMessages();
|
|
7692
7688
|
}
|
|
7693
|
-
this.
|
|
7689
|
+
this._finalizeSubmissionStream(requestId, submissionResult);
|
|
7694
7690
|
await this._fireResponseHook({
|
|
7695
7691
|
message: assistantMsg,
|
|
7696
7692
|
requestId,
|
|
@@ -7700,8 +7696,10 @@ var Think = class Think extends Agent {
|
|
|
7700
7696
|
});
|
|
7701
7697
|
} catch (e) {
|
|
7702
7698
|
console.error("Failed to persist assistant message:", e);
|
|
7699
|
+
streamError = e instanceof Error ? e.message : "Assistant message persistence failed";
|
|
7700
|
+
this._errorResumableStream(streamId, requestId);
|
|
7703
7701
|
}
|
|
7704
|
-
this.
|
|
7702
|
+
this._finalizeSubmissionStream(requestId, submissionResult);
|
|
7705
7703
|
this._onStreamingTurnFinalized();
|
|
7706
7704
|
return streamError ? {
|
|
7707
7705
|
status: "error",
|
|
@@ -7738,7 +7736,7 @@ var Think = class Think extends Agent {
|
|
|
7738
7736
|
* from it) or the message — never neither, never both. The session
|
|
7739
7737
|
* change feed and auto-compaction run once the transaction has committed.
|
|
7740
7738
|
*/
|
|
7741
|
-
async _persistAssistantMessageWithCutover(streamId, msg, parentId, options = {}) {
|
|
7739
|
+
async _persistAssistantMessageWithCutover(streamId, msg, parentId, options = {}, submission) {
|
|
7742
7740
|
const toPersist = this._strippedForPersist(msg);
|
|
7743
7741
|
if (toPersist === null) return;
|
|
7744
7742
|
if (this._resumableStream.pendingCutoverId !== streamId) {
|
|
@@ -7753,7 +7751,8 @@ var Think = class Think extends Agent {
|
|
|
7753
7751
|
parentId,
|
|
7754
7752
|
source: "server"
|
|
7755
7753
|
}).after;
|
|
7756
|
-
|
|
7754
|
+
if (submission) this._recordSubmissionTurnResult(submission.requestId, submission.result);
|
|
7755
|
+
}, options);
|
|
7757
7756
|
} catch (error) {
|
|
7758
7757
|
sync.abandon();
|
|
7759
7758
|
throw error;
|
|
@@ -7764,10 +7763,38 @@ var Think = class Think extends Agent {
|
|
|
7764
7763
|
* Whether this turn's stream rows can go with its cutover. An agent-tool
|
|
7765
7764
|
* child turn keeps them: the parent tails the stored chunks after the
|
|
7766
7765
|
* child completes (`getAgentToolChunks`), so the rows are reclaimed by
|
|
7767
|
-
* the child's next `start()` instead, as `AIChatAgent` does.
|
|
7766
|
+
* the child's next `start()` instead, as `AIChatAgent` does. A running
|
|
7767
|
+
* submission needs no stream evidence: its durable outcome stamp commits
|
|
7768
|
+
* in the same transaction as this cutover.
|
|
7768
7769
|
*/
|
|
7769
|
-
|
|
7770
|
-
return !this._agentToolRunsByRequestId.get(requestId);
|
|
7770
|
+
_streamCutoverOptions(requestId) {
|
|
7771
|
+
return { discard: !this._agentToolRunsByRequestId.get(requestId) };
|
|
7772
|
+
}
|
|
7773
|
+
/** Write only inside the transaction that settles this exact request's stream. */
|
|
7774
|
+
_recordSubmissionTurnResult(requestId, result) {
|
|
7775
|
+
const row = this._readRunningSubmissionForRecovery(requestId);
|
|
7776
|
+
if (!row || row.request_id !== requestId) return;
|
|
7777
|
+
this.sql`
|
|
7778
|
+
UPDATE cf_think_submissions
|
|
7779
|
+
SET result_status = ${result.status},
|
|
7780
|
+
output_json = ${result.status === "completed" && result.output !== void 0 ? JSON.stringify(result.output) : null}
|
|
7781
|
+
WHERE submission_id = ${row.submission_id} AND status = 'running'
|
|
7782
|
+
`;
|
|
7783
|
+
}
|
|
7784
|
+
/** Empty/stripped messages have the same atomic outcome cutover as messages. */
|
|
7785
|
+
_finalizeSubmissionStream(requestId, result) {
|
|
7786
|
+
if (this._resumableStream.pendingCutoverId === null) return;
|
|
7787
|
+
this.ctx.storage.transactionSync(() => {
|
|
7788
|
+
this._resumableStream.finalizePending();
|
|
7789
|
+
this._recordSubmissionTurnResult(requestId, result);
|
|
7790
|
+
});
|
|
7791
|
+
}
|
|
7792
|
+
/** Keep overflow chunks for consumers, but never call that segment an answer. */
|
|
7793
|
+
_completeSubmissionRetryStream(streamId, requestId) {
|
|
7794
|
+
this.ctx.storage.transactionSync(() => {
|
|
7795
|
+
this._completeResumableStream(streamId);
|
|
7796
|
+
this._recordSubmissionTurnResult(requestId, { status: "retry" });
|
|
7797
|
+
});
|
|
7771
7798
|
}
|
|
7772
7799
|
/**
|
|
7773
7800
|
* Remove parts belonging to Think's internal structured-output final-answer
|
|
@@ -8232,7 +8259,7 @@ var Think = class Think extends Agent {
|
|
|
8232
8259
|
break;
|
|
8233
8260
|
}
|
|
8234
8261
|
if (target) this._scheduleAutoContinuation(target);
|
|
8235
|
-
else this.
|
|
8262
|
+
else await this._queueConnectionlessContinuation();
|
|
8236
8263
|
return true;
|
|
8237
8264
|
}
|
|
8238
8265
|
/**
|
|
@@ -8574,7 +8601,7 @@ var Think = class Think extends Agent {
|
|
|
8574
8601
|
}, input.streamId, incident.firstSeenAt);
|
|
8575
8602
|
return "exhausted";
|
|
8576
8603
|
}
|
|
8577
|
-
const recoveredRequestId = this.
|
|
8604
|
+
const recoveredRequestId = this._readRunningSubmissionForRecovery(recoveryRootRequestId)?.submission_id;
|
|
8578
8605
|
await this._chatRecoveryEngine().scheduleRecovery({
|
|
8579
8606
|
incident,
|
|
8580
8607
|
recoveryKind: "continue",
|
|
@@ -8657,14 +8684,20 @@ var Think = class Think extends Agent {
|
|
|
8657
8684
|
};
|
|
8658
8685
|
}
|
|
8659
8686
|
/**
|
|
8660
|
-
* Classify a recovered turn as `retry` or `continue`. A
|
|
8661
|
-
* partial re-runs its user message (`retryTargetUserId`), unless
|
|
8662
|
-
* already terminal — a terminal stream is never retried (it
|
|
8663
|
-
* its submission is reconciled in dispatch.
|
|
8687
|
+
* Classify a recovered turn as `retry` or `continue`. A turn that left no
|
|
8688
|
+
* persisted partial re-runs its user message (`retryTargetUserId`), unless
|
|
8689
|
+
* the stream is already terminal — a terminal stream is never retried (it
|
|
8690
|
+
* completed), only its submission is reconciled in dispatch.
|
|
8691
|
+
*
|
|
8692
|
+
* The stream row is opened before inference, so an interrupted turn can
|
|
8693
|
+
* have a stream id and still nothing to continue from; what decides retry is
|
|
8694
|
+
* the absence of persisted content and a leaf that is still the turn's user
|
|
8695
|
+
* message. Mirrors `AIChatAgent`'s empty-partial new-turn rule (#1691): a
|
|
8696
|
+
* `continue` here would find no assistant message and skip the turn.
|
|
8664
8697
|
*/
|
|
8665
8698
|
async _classifyRecoveredThinkTurn(input) {
|
|
8666
8699
|
const streamIsTerminal = input.streamStatus === "completed" || input.streamStatus === "error";
|
|
8667
|
-
const retryTargetUserId = await this._recoverablePreStreamUserId(input.snapshot, input.
|
|
8700
|
+
const retryTargetUserId = await this._recoverablePreStreamUserId(input.snapshot, input.partial);
|
|
8668
8701
|
return {
|
|
8669
8702
|
recoveryKind: retryTargetUserId !== null && !streamIsTerminal ? "retry" : "continue",
|
|
8670
8703
|
detail: { retryTargetUserId }
|
|
@@ -8686,9 +8719,9 @@ var Think = class Think extends Agent {
|
|
|
8686
8719
|
const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();
|
|
8687
8720
|
const targetId = lastLeaf?.role === "assistant" && !streamIsTerminal ? lastLeaf.id : void 0;
|
|
8688
8721
|
const canContinue = !shouldRetry && options.continue !== false && !streamIsTerminal;
|
|
8689
|
-
const
|
|
8690
|
-
if (streamIsTerminal &&
|
|
8691
|
-
const recoveredRequestId = (canContinue || shouldRetry) &&
|
|
8722
|
+
const recoveredSubmission = this._readRunningSubmissionForRecovery(recoveryRootRequestId);
|
|
8723
|
+
if (streamIsTerminal && recoveredSubmission) await this._completeRecoveredSubmission(recoveryRootRequestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
|
|
8724
|
+
const recoveredRequestId = (canContinue || shouldRetry) && recoveredSubmission ? recoveredSubmission.submission_id : void 0;
|
|
8692
8725
|
if (shouldRetry) await this._chatRecoveryEngine().scheduleRecovery({
|
|
8693
8726
|
incident,
|
|
8694
8727
|
recoveryKind: input.recoveryKind,
|
|
@@ -8731,8 +8764,8 @@ var Think = class Think extends Agent {
|
|
|
8731
8764
|
});
|
|
8732
8765
|
} else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", streamIsTerminal ? "stream_terminal" : "not_recoverable");
|
|
8733
8766
|
}
|
|
8734
|
-
async _recoverablePreStreamUserId(snapshot,
|
|
8735
|
-
if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId ||
|
|
8767
|
+
async _recoverablePreStreamUserId(snapshot, partial) {
|
|
8768
|
+
if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || partial.text || partial.parts.length > 0) return null;
|
|
8736
8769
|
const lastLeaf = await this.session.getLatestLeaf();
|
|
8737
8770
|
return lastLeaf?.role === "user" && lastLeaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : null;
|
|
8738
8771
|
}
|
|
@@ -8959,7 +8992,7 @@ var Think = class Think extends Agent {
|
|
|
8959
8992
|
* down, so it throws too, burns the in-process retry budget inside the
|
|
8960
8993
|
* same reset window, and the row is consumed milliseconds before storage
|
|
8961
8994
|
* recovers. The submission is deliberately left `running` — the deferred
|
|
8962
|
-
* re-run reads it via `
|
|
8995
|
+
* re-run reads it via `_readRunningSubmissionForRecovery`, so marking it
|
|
8963
8996
|
* terminal here would turn the preserved row into a guaranteed
|
|
8964
8997
|
* `submission_not_running` no-op skip (a self-defeating defer).
|
|
8965
8998
|
* - Any OTHER (application) error is terminalized through the give-up path
|
|
@@ -8984,11 +9017,36 @@ var Think = class Think extends Agent {
|
|
|
8984
9017
|
console.error(`[Think] ${callback} threw during recovery; terminalizing instead of leaving the turn wedged`, error);
|
|
8985
9018
|
await this._exhaustRecoveryGiveUp(callback, data, "recovery_error");
|
|
8986
9019
|
}
|
|
9020
|
+
/**
|
|
9021
|
+
* Keep the recovery callback as owner until a chat Task or facet fiber is durably
|
|
9022
|
+
* accepted. At acceptance, move the running submission to the successor's
|
|
9023
|
+
* request identity before signaling handoff. If an override never starts a
|
|
9024
|
+
* durable successor, the signal stays inert and the callback owns the work
|
|
9025
|
+
* until the override returns.
|
|
9026
|
+
*/
|
|
9027
|
+
async _runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, run) {
|
|
9028
|
+
let signaled = false;
|
|
9029
|
+
const onAccepted = (successorRequestId) => {
|
|
9030
|
+
if (signaled) return;
|
|
9031
|
+
signaled = true;
|
|
9032
|
+
if (recoveredSubmission) this.sql`
|
|
9033
|
+
UPDATE cf_think_submissions
|
|
9034
|
+
SET request_id = ${successorRequestId}
|
|
9035
|
+
WHERE submission_id = ${recoveredSubmission.submission_id}
|
|
9036
|
+
AND status = 'running'
|
|
9037
|
+
`;
|
|
9038
|
+
onTurnStarted?.();
|
|
9039
|
+
};
|
|
9040
|
+
return recoveredTurnAcceptanceContext.run({
|
|
9041
|
+
agent: this,
|
|
9042
|
+
onAccepted
|
|
9043
|
+
}, run);
|
|
9044
|
+
}
|
|
8987
9045
|
async _chatRecoveryRetry(data) {
|
|
8988
9046
|
await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
|
|
8989
9047
|
}
|
|
8990
9048
|
async _chatRecoveryRetryDetached(data, onTurnStarted) {
|
|
8991
|
-
const recoveredSubmission = data?.recoveredRequestId ? this.
|
|
9049
|
+
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionForRecovery(data.recoveredRequestId) : null;
|
|
8992
9050
|
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
8993
9051
|
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
8994
9052
|
return;
|
|
@@ -9017,13 +9075,12 @@ var Think = class Think extends Agent {
|
|
|
9017
9075
|
return;
|
|
9018
9076
|
}
|
|
9019
9077
|
this._applyRecoveredRequestContext(data);
|
|
9020
|
-
onTurnStarted
|
|
9021
|
-
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? {
|
|
9078
|
+
const result = await this._runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, () => this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? {
|
|
9022
9079
|
signal: controller.signal,
|
|
9023
9080
|
trigger: "recovery-retry"
|
|
9024
|
-
} : { trigger: "recovery-retry" });
|
|
9081
|
+
} : { trigger: "recovery-retry" }));
|
|
9025
9082
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
9026
|
-
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
|
|
9083
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(recoveredSubmission ?? data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
|
|
9027
9084
|
} catch (error) {
|
|
9028
9085
|
await this._handleRecoveryCallbackError("_chatRecoveryRetry", data, error);
|
|
9029
9086
|
} finally {
|
|
@@ -9032,67 +9089,80 @@ var Think = class Think extends Agent {
|
|
|
9032
9089
|
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
9033
9090
|
}
|
|
9034
9091
|
}
|
|
9035
|
-
|
|
9036
|
-
|
|
9037
|
-
|
|
9038
|
-
|
|
9092
|
+
/**
|
|
9093
|
+
* Recovery payloads retain the original submission/root identity while
|
|
9094
|
+
* request_id follows the accepted successor. Match both so released payloads,
|
|
9095
|
+
* redeferred callbacks, and exhaustion can still locate the running row.
|
|
9096
|
+
* Exact submission identity wins even when terminal: a redelivery must not
|
|
9097
|
+
* fall through to another submission whose successor request collides.
|
|
9098
|
+
*/
|
|
9099
|
+
_readRunningSubmissionForRecovery(recoveredRequestId) {
|
|
9039
9100
|
this._ensureSubmissionTable();
|
|
9040
|
-
|
|
9101
|
+
const rows = this.sql`
|
|
9041
9102
|
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
9042
9103
|
messages_json, metadata_json, error_message, created_at,
|
|
9043
|
-
messages_applied_at, started_at, completed_at
|
|
9104
|
+
messages_applied_at, started_at, completed_at, result_status, output_json
|
|
9044
9105
|
FROM cf_think_submissions
|
|
9045
|
-
WHERE
|
|
9046
|
-
|
|
9106
|
+
WHERE submission_id = ${recoveredRequestId}
|
|
9107
|
+
OR (request_id = ${recoveredRequestId} AND status = 'running')
|
|
9108
|
+
ORDER BY (submission_id = ${recoveredRequestId}) DESC
|
|
9047
9109
|
LIMIT 1
|
|
9048
|
-
|
|
9110
|
+
`;
|
|
9111
|
+
return rows[0]?.status === "running" ? rows[0] : null;
|
|
9049
9112
|
}
|
|
9050
|
-
async _markRecoveredSubmissionInterrupted(
|
|
9051
|
-
this.
|
|
9052
|
-
const row = this.sql`
|
|
9053
|
-
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
9054
|
-
messages_json, metadata_json, error_message, created_at,
|
|
9055
|
-
messages_applied_at, started_at, completed_at
|
|
9056
|
-
FROM cf_think_submissions
|
|
9057
|
-
WHERE request_id = ${requestId}
|
|
9058
|
-
AND status = 'running'
|
|
9059
|
-
LIMIT 1
|
|
9060
|
-
`[0];
|
|
9113
|
+
async _markRecoveredSubmissionInterrupted(recoveredRequestId, message) {
|
|
9114
|
+
const row = this._readRunningSubmissionForRecovery(recoveredRequestId);
|
|
9061
9115
|
if (!row) return;
|
|
9062
9116
|
this.sql`
|
|
9063
9117
|
UPDATE cf_think_submissions
|
|
9064
9118
|
SET status = 'error',
|
|
9065
9119
|
error_message = ${message},
|
|
9066
|
-
completed_at = ${Date.now()}
|
|
9120
|
+
completed_at = ${Date.now()},
|
|
9121
|
+
result_status = NULL,
|
|
9122
|
+
output_json = NULL
|
|
9067
9123
|
WHERE submission_id = ${row.submission_id}
|
|
9068
9124
|
AND status = 'running'
|
|
9069
9125
|
`;
|
|
9070
9126
|
const updated = this._readSubmission(row.submission_id);
|
|
9071
|
-
if (updated
|
|
9127
|
+
if (updated?.status === "error") {
|
|
9128
|
+
this._enqueueTerminalWorkflowNotification(updated);
|
|
9129
|
+
await this._emitSubmissionStatus(updated);
|
|
9130
|
+
}
|
|
9072
9131
|
}
|
|
9073
|
-
async _completeRecoveredSubmission(
|
|
9074
|
-
this.
|
|
9132
|
+
async _completeRecoveredSubmission(recoveredSubmission, status, requestId, errorMessage) {
|
|
9133
|
+
const row = typeof recoveredSubmission === "string" ? this._readRunningSubmissionForRecovery(recoveredSubmission) : this._readSubmission(recoveredSubmission.submission_id);
|
|
9134
|
+
if (row?.status !== "running") return;
|
|
9135
|
+
let output;
|
|
9136
|
+
if (row.result_status === "completed" || row.result_status === "aborted") {
|
|
9137
|
+
status = row.result_status;
|
|
9138
|
+
errorMessage = null;
|
|
9139
|
+
if (status === "completed" && row.output_json !== null) output = JSON.parse(row.output_json);
|
|
9140
|
+
} else if (row.result_status === "error" && status === "completed") {
|
|
9141
|
+
status = "error";
|
|
9142
|
+
errorMessage = "Recovered chat stream had already errored.";
|
|
9143
|
+
} else if (row.result_status === "retry" && status === "completed") {
|
|
9144
|
+
if (row.request_id && this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || await this._hasScheduledChatRecovery(row)) return;
|
|
9145
|
+
await this._markRecoveredSubmissionInterrupted(row.submission_id, "Submission was interrupted after messages were applied.");
|
|
9146
|
+
return;
|
|
9147
|
+
}
|
|
9075
9148
|
const completedAt = Date.now();
|
|
9076
|
-
const streamId = requestId ? this._resumableStream.
|
|
9077
|
-
this.
|
|
9078
|
-
|
|
9079
|
-
|
|
9080
|
-
|
|
9081
|
-
|
|
9082
|
-
|
|
9083
|
-
|
|
9084
|
-
|
|
9085
|
-
|
|
9086
|
-
|
|
9087
|
-
|
|
9088
|
-
|
|
9089
|
-
|
|
9090
|
-
|
|
9091
|
-
|
|
9092
|
-
|
|
9093
|
-
ORDER BY completed_at DESC
|
|
9094
|
-
LIMIT 1
|
|
9095
|
-
`[0];
|
|
9149
|
+
const streamId = requestId ? this._resumableStream.latestStreamInfoForRequest(requestId)?.id ?? null : null;
|
|
9150
|
+
this.ctx.storage.transactionSync(() => {
|
|
9151
|
+
this.sql`
|
|
9152
|
+
UPDATE cf_think_submissions
|
|
9153
|
+
SET status = ${status},
|
|
9154
|
+
request_id = COALESCE(${requestId}, request_id),
|
|
9155
|
+
stream_id = COALESCE(${streamId}, stream_id),
|
|
9156
|
+
error_message = ${errorMessage},
|
|
9157
|
+
completed_at = ${completedAt},
|
|
9158
|
+
result_status = NULL,
|
|
9159
|
+
output_json = NULL
|
|
9160
|
+
WHERE submission_id = ${row.submission_id}
|
|
9161
|
+
AND status = 'running'
|
|
9162
|
+
`;
|
|
9163
|
+
this._enqueueTerminalWorkflowNotification(this._readSubmission(row.submission_id), output);
|
|
9164
|
+
});
|
|
9165
|
+
const updated = this._readSubmission(row.submission_id);
|
|
9096
9166
|
if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
|
|
9097
9167
|
}
|
|
9098
9168
|
async onChatRecovery(_ctx) {
|
|
@@ -9102,7 +9172,7 @@ var Think = class Think extends Agent {
|
|
|
9102
9172
|
await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
|
|
9103
9173
|
}
|
|
9104
9174
|
async _chatRecoveryContinueDetached(data, onTurnStarted) {
|
|
9105
|
-
const recoveredSubmission = data?.recoveredRequestId ? this.
|
|
9175
|
+
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionForRecovery(data.recoveredRequestId) : null;
|
|
9106
9176
|
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
9107
9177
|
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
9108
9178
|
return;
|
|
@@ -9129,13 +9199,12 @@ var Think = class Think extends Agent {
|
|
|
9129
9199
|
return;
|
|
9130
9200
|
}
|
|
9131
9201
|
this._applyRecoveredRequestContext(data);
|
|
9132
|
-
onTurnStarted
|
|
9133
|
-
const result = await this.continueLastTurn(void 0, controller ? {
|
|
9202
|
+
const result = await this._runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, () => this.continueLastTurn(void 0, controller ? {
|
|
9134
9203
|
signal: controller.signal,
|
|
9135
9204
|
trigger: "recovery-continue"
|
|
9136
|
-
} : { trigger: "recovery-continue" });
|
|
9205
|
+
} : { trigger: "recovery-continue" }));
|
|
9137
9206
|
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
9138
|
-
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
|
|
9207
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(recoveredSubmission ?? data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
|
|
9139
9208
|
} catch (error) {
|
|
9140
9209
|
await this._handleRecoveryCallbackError("_chatRecoveryContinue", data, error);
|
|
9141
9210
|
} finally {
|
|
@@ -9304,54 +9373,59 @@ var Think = class Think extends Agent {
|
|
|
9304
9373
|
this._autoContinuation.activateDeferredAndReschedule();
|
|
9305
9374
|
}
|
|
9306
9375
|
/**
|
|
9307
|
-
*
|
|
9376
|
+
* Queue a continuation turn that does NOT require a live client connection.
|
|
9308
9377
|
*
|
|
9309
9378
|
* Used when a durable approval (a paused action or codemode execution) is
|
|
9310
9379
|
* resolved via RPC from a surface with no open chat socket — e.g. an ops
|
|
9311
9380
|
* dashboard, a webhook, or a voice backend approving hours/days later. The
|
|
9312
|
-
*
|
|
9313
|
-
*
|
|
9314
|
-
*
|
|
9315
|
-
*
|
|
9316
|
-
*
|
|
9317
|
-
* Wrapped in `keepAliveWhile` because the resolving RPC returns before the
|
|
9318
|
-
* continuation finishes (mirrors the submission-drain pattern).
|
|
9381
|
+
* item is durable, so the turn still runs if the object leaves memory
|
|
9382
|
+
* before the alarm fires; the last request body and client tools it needs
|
|
9383
|
+
* are persisted config, restored on start. Approvals landing while one
|
|
9384
|
+
* continuation is pending or running coalesce onto the single item.
|
|
9319
9385
|
*/
|
|
9320
|
-
|
|
9321
|
-
this.
|
|
9322
|
-
|
|
9323
|
-
|
|
9324
|
-
|
|
9325
|
-
|
|
9326
|
-
|
|
9327
|
-
|
|
9328
|
-
|
|
9329
|
-
|
|
9330
|
-
|
|
9331
|
-
|
|
9332
|
-
|
|
9333
|
-
|
|
9334
|
-
|
|
9335
|
-
|
|
9336
|
-
|
|
9337
|
-
|
|
9338
|
-
|
|
9339
|
-
|
|
9340
|
-
|
|
9341
|
-
|
|
9342
|
-
|
|
9343
|
-
|
|
9344
|
-
|
|
9345
|
-
|
|
9346
|
-
|
|
9347
|
-
|
|
9348
|
-
|
|
9349
|
-
|
|
9350
|
-
|
|
9351
|
-
|
|
9352
|
-
|
|
9353
|
-
|
|
9354
|
-
|
|
9386
|
+
async _queueConnectionlessContinuation() {
|
|
9387
|
+
await this.queue(CONNECTIONLESS_CONTINUATION_CALLBACK, void 0, { id: "connectionless-continuation" });
|
|
9388
|
+
}
|
|
9389
|
+
/**
|
|
9390
|
+
* Run one connection-less continuation turn. Mirrors the connection-bound
|
|
9391
|
+
* auto-continuation turn body but streams via `broadcast` (a no-op when
|
|
9392
|
+
* nobody is attached) and always persists, so a client that reconnects
|
|
9393
|
+
* later resumes the continued turn from history.
|
|
9394
|
+
* @internal Queue callback.
|
|
9395
|
+
*/
|
|
9396
|
+
async _cfRunConnectionlessContinuation() {
|
|
9397
|
+
const requestId = crypto.randomUUID();
|
|
9398
|
+
const abortSignal = this._aborts.getSignal(requestId);
|
|
9399
|
+
try {
|
|
9400
|
+
await this._admitTurn({
|
|
9401
|
+
admission: "queue",
|
|
9402
|
+
trigger: "auto-continuation",
|
|
9403
|
+
requestId,
|
|
9404
|
+
continuation: true,
|
|
9405
|
+
allowNested: true,
|
|
9406
|
+
execute: async () => {
|
|
9407
|
+
const continuationBody = async () => {
|
|
9408
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
9409
|
+
agent: this,
|
|
9410
|
+
connection: void 0,
|
|
9411
|
+
request: void 0,
|
|
9412
|
+
email: void 0
|
|
9413
|
+
}, () => this._runInferenceLoop({
|
|
9414
|
+
signal: abortSignal,
|
|
9415
|
+
clientTools: this._lastClientTools,
|
|
9416
|
+
body: this._lastBody,
|
|
9417
|
+
continuation: true
|
|
9418
|
+
}));
|
|
9419
|
+
if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
|
|
9420
|
+
};
|
|
9421
|
+
await this._runChatRecoveryFiber(requestId, true, continuationBody);
|
|
9422
|
+
}
|
|
9423
|
+
});
|
|
9424
|
+
} catch (error) {
|
|
9425
|
+
console.error("[Think] Connection-less continuation failed:", error);
|
|
9426
|
+
} finally {
|
|
9427
|
+
this._aborts.remove(requestId);
|
|
9428
|
+
}
|
|
9355
9429
|
}
|
|
9356
9430
|
/**
|
|
9357
9431
|
* Render a reply attachment ({@link ReplyAttachment}) for delivery to the
|
|
@@ -9547,8 +9621,11 @@ var Think = class Think extends Agent {
|
|
|
9547
9621
|
this._resumableStream.finish(streamId);
|
|
9548
9622
|
}
|
|
9549
9623
|
/** Mark a resumable stream errored. */
|
|
9550
|
-
_errorResumableStream(streamId) {
|
|
9551
|
-
this.
|
|
9624
|
+
_errorResumableStream(streamId, requestId) {
|
|
9625
|
+
this.ctx.storage.transactionSync(() => {
|
|
9626
|
+
this._resumableStream.markError(streamId);
|
|
9627
|
+
if (requestId) this._recordSubmissionTurnResult(requestId, { status: "error" });
|
|
9628
|
+
});
|
|
9552
9629
|
}
|
|
9553
9630
|
/**
|
|
9554
9631
|
* @deprecated Streams are reclaimed at cutover and on the next stream
|