@sentry/junior 0.284.0 → 0.286.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/{adapter-CW5UW7vL.js → adapter-JQZaJ-B_.js} +37 -3
- package/dist/{admin-DUWN8zZX.js → admin-Dm2bimJ-.js} +1 -1
- package/dist/{agent-runner-Cqr21pOU.js → agent-runner-DGCwOEyL.js} +2180 -2735
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +8 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +166 -90
- package/dist/{app-CvGalMxi.d.ts → app-BKq0JzWx.d.ts} +2 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +225 -188
- package/dist/{assistant-reply-CFE-OZMS.js → assistant-reply-CAPafcUY.js} +1 -1
- package/dist/{automation-Zvx_I9Z5.js → automation-B-jJN_gM.js} +1 -1
- package/dist/{background-compaction-queue-CHFzrQbS.js → background-compaction-queue-Btu2oab_.js} +137 -3
- package/dist/{briefs-Cx7mkfSk.js → briefs-UMeYehUe.js} +5 -5
- package/dist/{catalog-runtime-dKOVbR7l.js → catalog-runtime-Bym8GVdh.js} +1 -1
- package/dist/cli/chat.js +19 -16
- package/dist/cli/check.js +3 -3
- package/dist/cli/init.js +3 -0
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +12 -17
- package/dist/{client-CMyH5rDz.js → client-B0aAs7wC.js} +2 -2
- package/dist/{config-Dt3CpG17.js → config-B9f9Lqo5.js} +1 -1
- package/dist/{connections-CCHPybZP.js → connections-CQ7p0aNJ.js} +16 -50
- package/dist/{conversation-DdT7SNar.js → conversation-BusI2uzj.js} +68 -7
- package/dist/{conversation-pending-messages-Dct5pheX.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
- package/dist/{conversation-privacy-BpHHhEVp.js → conversation-privacy-Cd_nZZBM.js} +1 -1
- package/dist/{credential-sync-BBPw8dam.js → credential-sync-DmiJi_At.js} +13 -13
- package/dist/{db-D7CCwAo8.d.ts → db-C5zi4ecs.d.ts} +18 -2
- package/dist/{executor-CyIwHz9r.js → executor-Dipi2Ixl.js} +19 -17
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-Qo-7xGp1.js → logging-CMFhLLj4.js} +1 -1
- package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
- package/dist/{message-DFbtOWqv.js → message-D1xLljUF.js} +13 -23
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -3
- package/dist/{oauth-callback-server-BB1gixWo.js → oauth-callback-server-DCAFIUQr.js} +2 -2
- package/dist/{projection-0UcUeuzn.js → projection-CoeMNxJ4.js} +545 -262
- package/dist/{prompt-CCtaGgbI.js → prompt-C9OQEfan.js} +8 -6
- package/dist/{registry-DOnPkI8g.js → registry-u-sFYtx_.js} +1 -1
- package/dist/{reporting-window-B-QP9zX1.js → reporting-window-B4TwyuJo.js} +14 -14
- package/dist/{resolve-Di3omymY.js → resolve-DYqgL3Eo.js} +3 -3
- package/dist/result-CescSwAw.js +299 -0
- package/dist/result-event-type-DD6BAgT7.js +11 -0
- package/dist/{runner-CnX_dTKw.js → runner-Cr67a8TB.js} +16 -12
- package/dist/{sandbox-egress-signals-CtxLJmmg.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
- package/dist/{schema-Bn3miEd_.js → schema-BUSi3sgv.js} +63 -5
- package/dist/{schema-B017enNE.d.ts → schema-Ih60j59-.d.ts} +194 -220
- package/dist/{service-account-KhZIqXRi.js → service-account-CGEqz9wG.js} +3 -3
- package/dist/{service-account-ewDAx4Mx.js → service-account-CsKxktLk.js} +3 -3
- package/dist/session-stop-CGz5DByb.js +2926 -0
- package/dist/{skills-CKyotM4g.js → skills-COCqf61f.js} +2 -2
- package/dist/{spawn-D5D2MQdz.js → spawn-C8F_iXWO.js} +13 -2
- package/dist/{stop-BSKRTaRS.js → stop-GyFZkHuQ.js} +7730 -7818
- package/dist/{store-ymkEUWe4.js → store-D0-8plWp.js} +30 -5
- package/dist/{turn-session-routing-D_GXfcAG.js → task-runner-xPuQmEot.js} +1440 -994
- package/dist/{store-G3S0kWSD.js → turn-failure-response-BOviBdT-.js} +404 -311
- package/dist/{validation-DJG_wrg2.js → validation-DZDKorGz.js} +1 -1
- package/dist/{version-i1An1eTS.js → version-BTIz7fGi.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BlpnzZZa.js → viewer-CH-ASQzh.js} +208 -68
- package/dist/{work-BgCW3FDC.js → work-C75_IM5e.js} +311 -100
- package/dist/{worker-BJz1mwYt.js → worker-Dl47I729.js} +6 -6
- package/migrations/0083_conversation_kind.sql +11 -0
- package/migrations/0084_read_position_backfill.sql +25 -0
- package/migrations/0085_child_archived_at.sql +1 -0
- package/migrations/0086_shared_archive.sql +31 -0
- package/migrations/0087_child_location.sql +64 -0
- package/migrations/meta/0083_snapshot.json +4388 -0
- package/migrations/meta/0084_snapshot.json +4388 -0
- package/migrations/meta/0085_snapshot.json +4394 -0
- package/migrations/meta/0086_snapshot.json +4366 -0
- package/migrations/meta/0087_snapshot.json +4366 -0
- package/migrations/meta/_journal.json +35 -0
- package/package.json +5 -4
- package/dist/result-NvndYzCb.js +0 -483
- package/dist/session-stop-D_1SysjC.js +0 -1438
- package/dist/task-queue-BcOHzXxe.js +0 -139
- package/dist/task-runner-B65cDumh.js +0 -290
- package/dist/thread-state-D6rNGQu9.js +0 -173
- package/dist/turn-failure-response-BlO4nuDJ.js +0 -224
- package/dist/turn-lifecycle-BQ8ETk63.js +0 -58
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
import { h as logWarn } from "./logging-Qo-7xGp1.js";
|
|
2
|
-
import { _ as runWithTurnRequestDeadline, f as QUEUE_SIGNATURE_MAX_AGE_MS, h as getQueueProvider, m as verifyQueueMessage, p as signQueueMessage } from "./background-compaction-queue-CHFzrQbS.js";
|
|
3
|
-
import { createHash } from "node:crypto";
|
|
4
|
-
import * as z from "zod";
|
|
5
|
-
// src/chat/queue/callback.ts
|
|
6
|
-
/** Shared queue callback wiring for signed messages. */
|
|
7
|
-
/** Build the HTTP callback and local-dev consumer for one signed queue. */
|
|
8
|
-
function queueCallback(options) {
|
|
9
|
-
const consume = async (message, metadata) => {
|
|
10
|
-
if (options.skip?.(metadata)) return;
|
|
11
|
-
try {
|
|
12
|
-
await runWithTurnRequestDeadline(() => options.run(message, metadata));
|
|
13
|
-
} catch (error) {
|
|
14
|
-
const reason = options.permanentError?.(error);
|
|
15
|
-
if (!reason) throw error;
|
|
16
|
-
options.onRejected(reason, metadata, error);
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
const handler = async (value, metadata) => {
|
|
20
|
-
if (options.skip?.(metadata)) return;
|
|
21
|
-
const checked = options.verify(value);
|
|
22
|
-
if (checked.status === "rejected") {
|
|
23
|
-
options.onRejected(checked.reason, metadata);
|
|
24
|
-
return;
|
|
25
|
-
}
|
|
26
|
-
if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
|
|
27
|
-
await consume(checked.message, metadata);
|
|
28
|
-
};
|
|
29
|
-
const retry = (error, metadata) => {
|
|
30
|
-
const reason = options.permanentError?.(error);
|
|
31
|
-
if (reason) {
|
|
32
|
-
options.onRejected(reason, metadata, error);
|
|
33
|
-
return { acknowledge: true };
|
|
34
|
-
}
|
|
35
|
-
if (options.maxDeliveries !== null && metadata.deliveryCount >= options.maxDeliveries) return { acknowledge: true };
|
|
36
|
-
};
|
|
37
|
-
const consumer = {
|
|
38
|
-
consumerGroup: options.consumerGroup,
|
|
39
|
-
handler,
|
|
40
|
-
retry,
|
|
41
|
-
topic: options.topic,
|
|
42
|
-
visibilityTimeoutSeconds: options.visibilityTimeoutSeconds
|
|
43
|
-
};
|
|
44
|
-
return {
|
|
45
|
-
/** Run a message that an in-process queue already trusts. */
|
|
46
|
-
consume,
|
|
47
|
-
consumer,
|
|
48
|
-
create: () => getQueueProvider().createCallback(consumer),
|
|
49
|
-
registerDev: () => {
|
|
50
|
-
if (process.env.NODE_ENV !== "development") return;
|
|
51
|
-
return getQueueProvider().registerDevConsumer?.(consumer);
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
// src/chat/plugins/task-queue.ts
|
|
56
|
-
/**
|
|
57
|
-
* Delivery for plugin-registered tasks.
|
|
58
|
-
*
|
|
59
|
-
* Plugins register named tasks. This module owns the shared signed message,
|
|
60
|
-
* send path, and HTTP/local callback. Core keeps one topic and one runner.
|
|
61
|
-
*/
|
|
62
|
-
/** Deploy topic name. Keep stable for Vercel queue wiring. */
|
|
63
|
-
const PLUGIN_TASK_QUEUE_TOPIC = "junior_plugin_tasks";
|
|
64
|
-
const PLUGIN_TASK_DEV_CONSUMER_GROUP = "junior_plugin_tasks_dev";
|
|
65
|
-
const PLUGIN_TASK_MAX_DELIVERIES = 5;
|
|
66
|
-
const PLUGIN_TASK_SIGN_CONTEXT = "junior.plugin_task_queue.v1";
|
|
67
|
-
const PLUGIN_TASK_SIGN_VERSION = "v1";
|
|
68
|
-
const pluginTaskParamsSchema = z.object({
|
|
69
|
-
conversationId: z.string().min(1),
|
|
70
|
-
sessionId: z.string().min(1)
|
|
71
|
-
}).strict();
|
|
72
|
-
const pluginTaskSign = {
|
|
73
|
-
context: PLUGIN_TASK_SIGN_CONTEXT,
|
|
74
|
-
schema: z.object({
|
|
75
|
-
name: z.string().min(1),
|
|
76
|
-
params: pluginTaskParamsSchema,
|
|
77
|
-
plugin: z.string().min(1)
|
|
78
|
-
}).strict(),
|
|
79
|
-
signatureVersion: PLUGIN_TASK_SIGN_VERSION,
|
|
80
|
-
parts: (message) => [
|
|
81
|
-
message.plugin,
|
|
82
|
-
message.name,
|
|
83
|
-
message.params.conversationId,
|
|
84
|
-
message.params.sessionId
|
|
85
|
-
]
|
|
86
|
-
};
|
|
87
|
-
/** Build the stable id used for delivery dedupe and tracing. */
|
|
88
|
-
function pluginTaskId(args) {
|
|
89
|
-
return `plugin-task_${createHash("sha256").update(args.plugin).update("\0").update(args.name).update("\0").update(args.params.conversationId).update("\0").update(args.params.sessionId).digest("hex").slice(0, 32)}`;
|
|
90
|
-
}
|
|
91
|
-
/** Sign a plugin task message for tests and local checks. */
|
|
92
|
-
function signPluginTaskQueueMessage(message, nowMs = Date.now()) {
|
|
93
|
-
return signQueueMessage(pluginTaskSign, message, nowMs);
|
|
94
|
-
}
|
|
95
|
-
function verifyPluginTaskQueueMessage(value, nowMs = Date.now()) {
|
|
96
|
-
return verifyQueueMessage(pluginTaskSign, value, nowMs);
|
|
97
|
-
}
|
|
98
|
-
function logPluginTaskQueueMessageRejected(reason, metadata) {
|
|
99
|
-
logWarn("plugin.task.queue_message.rejected", {
|
|
100
|
-
"app.queue.consumer_group": metadata.consumerGroup,
|
|
101
|
-
"app.queue.delivery_count": metadata.deliveryCount,
|
|
102
|
-
"app.queue.message_id": metadata.messageId,
|
|
103
|
-
"app.queue.reject_reason": reason,
|
|
104
|
-
"app.queue.topic_name": metadata.topicName
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
function pluginTaskCallback() {
|
|
108
|
-
return queueCallback({
|
|
109
|
-
consumerGroup: PLUGIN_TASK_DEV_CONSUMER_GROUP,
|
|
110
|
-
maxDeliveries: PLUGIN_TASK_MAX_DELIVERIES,
|
|
111
|
-
onRejected: logPluginTaskQueueMessageRejected,
|
|
112
|
-
run: async (message) => {
|
|
113
|
-
const { processPluginTask } = await import("./task-runner-B65cDumh.js").then((n) => n.r);
|
|
114
|
-
await processPluginTask(message);
|
|
115
|
-
},
|
|
116
|
-
topic: PLUGIN_TASK_QUEUE_TOPIC,
|
|
117
|
-
verify: verifyPluginTaskQueueMessage
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
/** Send one plugin task through the shared signed delivery path. */
|
|
121
|
-
async function sendVercelPluginTask(message) {
|
|
122
|
-
await getQueueProvider().send(PLUGIN_TASK_QUEUE_TOPIC, signPluginTaskQueueMessage(message), {
|
|
123
|
-
idempotencyKey: pluginTaskId(message),
|
|
124
|
-
retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
|
-
/** Create the HTTP callback for plugin tasks. */
|
|
128
|
-
function createVercelPluginTaskCallback() {
|
|
129
|
-
return pluginTaskCallback().create();
|
|
130
|
-
}
|
|
131
|
-
/** Return the queue consumer for plugin tasks, for a pulling queue worker. */
|
|
132
|
-
function pluginTaskQueueConsumer() {
|
|
133
|
-
return pluginTaskCallback().consumer;
|
|
134
|
-
}
|
|
135
|
-
/** Register the local-dev consumer for plugin tasks. */
|
|
136
|
-
function registerVercelPluginTaskDevConsumer() {
|
|
137
|
-
return pluginTaskCallback().registerDev();
|
|
138
|
-
}
|
|
139
|
-
export { pluginTaskQueueConsumer as a, queueCallback as c, pluginTaskParamsSchema as i, createVercelPluginTaskCallback as n, registerVercelPluginTaskDevConsumer as o, pluginTaskId as r, sendVercelPluginTask as s, PLUGIN_TASK_QUEUE_TOPIC as t };
|
|
@@ -1,290 +0,0 @@
|
|
|
1
|
-
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { $a as createPluginConversationEvents, Bn as coreTaskRegistrations, Co as createPluginCache, Gt as getPiMessageRole, Ln as getPlugins, Ra as createPluginModelCostRecorder, Ta as createPluginModel, Xt as instructionTextForProjection, ei as createPluginState, en as isToolResultError, in as stripRuntimeTurnContext, nn as normalizeToolNameFromResult, tn as isToolResultMessage, tt as getTurnRecord, v as hydrateConversationMessages, wa as createPluginEmbedder, za as createPluginLogger } from "./projection-0UcUeuzn.js";
|
|
3
|
-
import { E as withSpan } from "./logging-Qo-7xGp1.js";
|
|
4
|
-
import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
|
|
5
|
-
import { S as getDb, i as readActorIdentity, x as getConversationStore } from "./viewer-BlpnzZZa.js";
|
|
6
|
-
import { v as sameActorIdentity } from "./media-Bu9C6lz0.js";
|
|
7
|
-
import { r as getStateAdapter } from "./adapter-CW5UW7vL.js";
|
|
8
|
-
import { t as resolveConversationRouting, u as getDispatchRecord } from "./turn-session-routing-D_GXfcAG.js";
|
|
9
|
-
import { o as coerceThreadConversationState, r as getPersistedThreadState } from "./thread-state-D6rNGQu9.js";
|
|
10
|
-
import { i as pluginTaskParamsSchema, r as pluginTaskId, s as sendVercelPluginTask } from "./task-queue-BcOHzXxe.js";
|
|
11
|
-
import { pluginRunContextSchema } from "@sentry/junior-plugin-api";
|
|
12
|
-
// src/chat/plugins/task-runner.ts
|
|
13
|
-
/**
|
|
14
|
-
* Plugin background-task orchestration.
|
|
15
|
-
*
|
|
16
|
-
* Core schedules tasks from completed sessions and exposes plugins only a
|
|
17
|
-
* bounded run projection rather than live runtime internals or queue
|
|
18
|
-
* payloads.
|
|
19
|
-
*/
|
|
20
|
-
var task_runner_exports = /* @__PURE__ */ __exportAll({
|
|
21
|
-
processPluginTask: () => processPluginTask,
|
|
22
|
-
scheduleSessionCompletedPluginTasks: () => scheduleSessionCompletedPluginTasks
|
|
23
|
-
});
|
|
24
|
-
const PLUGIN_TASK_LOCK_TTL_MS = 3e5;
|
|
25
|
-
function isRecord(value) {
|
|
26
|
-
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
27
|
-
}
|
|
28
|
-
function textPart(value) {
|
|
29
|
-
if (isRecord(value) && value.type === "text" && typeof value.text === "string") return value.text;
|
|
30
|
-
}
|
|
31
|
-
function messageText(message) {
|
|
32
|
-
const content = message.content;
|
|
33
|
-
if (typeof content === "string") return sanitizeText(content);
|
|
34
|
-
if (!Array.isArray(content)) return "";
|
|
35
|
-
return sanitizeText(content.map(textPart).filter(Boolean).join("\n"));
|
|
36
|
-
}
|
|
37
|
-
function toolResultText(message) {
|
|
38
|
-
const record = message;
|
|
39
|
-
return sanitizeText([
|
|
40
|
-
messageText(message),
|
|
41
|
-
record.output,
|
|
42
|
-
record.result,
|
|
43
|
-
record.stdout,
|
|
44
|
-
record.stderr,
|
|
45
|
-
record.toolResult
|
|
46
|
-
].filter((value) => typeof value === "string" && value.length > 0).join("\n"));
|
|
47
|
-
}
|
|
48
|
-
function sanitizeText(text) {
|
|
49
|
-
return text.replace(/<data_base64>[\s\S]*?<\/data_base64>/g, "<data_base64>[omitted]</data_base64>").replace(/data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+/gi, "[image data omitted]").replaceAll("\0", " ").trim();
|
|
50
|
-
}
|
|
51
|
-
/** Build the transcript provenance for a user message from its Pi provenance. */
|
|
52
|
-
function messageProvenance(provenance) {
|
|
53
|
-
return {
|
|
54
|
-
authority: provenance.authority,
|
|
55
|
-
...provenance.actor ? { actor: provenance.actor } : void 0
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
function runTranscriptEntry(message, provenance, runActor) {
|
|
59
|
-
const role = getPiMessageRole(message);
|
|
60
|
-
if (role === "user" || role === "assistant") {
|
|
61
|
-
const text = role === "user" ? instructionTextForProjection(messageText(message)) : messageText(message);
|
|
62
|
-
if (!text) return;
|
|
63
|
-
if (role === "assistant") return {
|
|
64
|
-
type: "message",
|
|
65
|
-
role,
|
|
66
|
-
text
|
|
67
|
-
};
|
|
68
|
-
return {
|
|
69
|
-
type: "message",
|
|
70
|
-
role,
|
|
71
|
-
text,
|
|
72
|
-
provenance: messageProvenance(provenance),
|
|
73
|
-
isRunActor: sameActorIdentity(provenance.actor, runActor)
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
if (!isToolResultMessage(message)) return;
|
|
77
|
-
const toolName = normalizeToolNameFromResult(message);
|
|
78
|
-
if (!toolName) return;
|
|
79
|
-
const text = toolResultText(message);
|
|
80
|
-
return {
|
|
81
|
-
type: "toolResult",
|
|
82
|
-
toolName,
|
|
83
|
-
isError: isToolResultError(message),
|
|
84
|
-
...text ? { text } : void 0
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Slice the current turn's Pi messages with their aligned provenance and strip
|
|
89
|
-
* runtime turn context, keeping each surviving message paired with the exact
|
|
90
|
-
* provenance recorded for it. Stripping can drop or rewrite messages, so the
|
|
91
|
-
* pairing is applied per message rather than by post-strip index.
|
|
92
|
-
*/
|
|
93
|
-
function turnMessagesWithProvenance(record) {
|
|
94
|
-
const startIndex = record.turnStartMessageIndex ?? 0;
|
|
95
|
-
const messages = record.piMessages.slice(startIndex);
|
|
96
|
-
const provenance = record.piMessageProvenance.slice(startIndex);
|
|
97
|
-
const paired = [];
|
|
98
|
-
for (const [index, message] of messages.entries()) for (const stripped of stripRuntimeTurnContext([message])) paired.push({
|
|
99
|
-
message: stripped,
|
|
100
|
-
provenance: provenance[index] ?? { authority: "context" }
|
|
101
|
-
});
|
|
102
|
-
return paired;
|
|
103
|
-
}
|
|
104
|
-
/** Recover the Slack context author identity from a persisted thread message. */
|
|
105
|
-
function slackContextAuthor(location, message) {
|
|
106
|
-
const userId = message.author?.userId?.trim();
|
|
107
|
-
if (!userId) return;
|
|
108
|
-
return {
|
|
109
|
-
platform: "slack",
|
|
110
|
-
teamId: location.teamId,
|
|
111
|
-
userId,
|
|
112
|
-
...message.author?.userName ? { userName: message.author.userName } : void 0,
|
|
113
|
-
...message.author?.fullName ? { fullName: message.author.fullName } : void 0
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
function slackTimestampMs(value) {
|
|
117
|
-
const timestamp = parseSlackMessageTs(value);
|
|
118
|
-
if (!timestamp) return;
|
|
119
|
-
const timestampMs = Number(timestamp) * 1e3;
|
|
120
|
-
return Number.isFinite(timestampMs) ? timestampMs : void 0;
|
|
121
|
-
}
|
|
122
|
-
function conversationMessageTimestampMs(message) {
|
|
123
|
-
if (message.meta?.slackTs !== void 0) return slackTimestampMs(message.meta.slackTs);
|
|
124
|
-
return Number.isFinite(message.createdAtMs) ? message.createdAtMs : void 0;
|
|
125
|
-
}
|
|
126
|
-
function messageExistedAtRunCompletion(message, completedAtMs) {
|
|
127
|
-
const messageTimestampMs = conversationMessageTimestampMs(message);
|
|
128
|
-
return messageTimestampMs !== void 0 && messageTimestampMs <= completedAtMs;
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Project bounded public-thread context into the run transcript.
|
|
132
|
-
*
|
|
133
|
-
* Prior public Slack messages from the current Conversation are durable
|
|
134
|
-
* evidence a completed run may have acted on, so passive consumers can cite
|
|
135
|
-
* them. They are always context authority (never instruction), and private or
|
|
136
|
-
* local Conversations add nothing here.
|
|
137
|
-
*/
|
|
138
|
-
async function loadConversationContextTranscriptEntries(record, location, visibility, runActor) {
|
|
139
|
-
if (location?.provider !== "slack" || visibility !== "public") return [];
|
|
140
|
-
const state = await getPersistedThreadState(record.conversationId);
|
|
141
|
-
const conversation = coerceThreadConversationState(state);
|
|
142
|
-
await hydrateConversationMessages({
|
|
143
|
-
conversation,
|
|
144
|
-
conversationId: record.conversationId
|
|
145
|
-
});
|
|
146
|
-
const entries = [];
|
|
147
|
-
for (const message of conversation.messages) {
|
|
148
|
-
if (message.role !== "user") continue;
|
|
149
|
-
if (!messageExistedAtRunCompletion(message, record.updatedAtMs)) continue;
|
|
150
|
-
const text = sanitizeText(message.text);
|
|
151
|
-
if (!text) continue;
|
|
152
|
-
const author = slackContextAuthor(location, message);
|
|
153
|
-
entries.push({
|
|
154
|
-
type: "message",
|
|
155
|
-
role: "user",
|
|
156
|
-
text,
|
|
157
|
-
provenance: {
|
|
158
|
-
authority: "context",
|
|
159
|
-
...author ? { actor: author } : void 0
|
|
160
|
-
},
|
|
161
|
-
isRunActor: sameActorIdentity(author, runActor)
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
return entries;
|
|
165
|
-
}
|
|
166
|
-
async function withPluginTaskLock(taskId, callback) {
|
|
167
|
-
const state = getStateAdapter();
|
|
168
|
-
await state.connect();
|
|
169
|
-
const lock = await state.acquireLock(`plugin:task:${taskId}`, PLUGIN_TASK_LOCK_TTL_MS);
|
|
170
|
-
if (!lock) throw new Error(`Could not acquire plugin task lock for ${taskId}`);
|
|
171
|
-
try {
|
|
172
|
-
return await callback();
|
|
173
|
-
} finally {
|
|
174
|
-
await state.releaseLock(lock);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
/** Load the bounded completed-run projection exposed to plugin tasks. */
|
|
178
|
-
async function loadPluginRun(params) {
|
|
179
|
-
const record = await getTurnRecord(params.conversationId, params.sessionId);
|
|
180
|
-
if (!record) throw new Error("Completed plugin task session record is unavailable");
|
|
181
|
-
if (record.state !== "completed") throw new Error("Completed plugin task session record is not completed");
|
|
182
|
-
const conversationStore = getConversationStore();
|
|
183
|
-
const routing = await resolveConversationRouting({
|
|
184
|
-
conversationId: params.conversationId,
|
|
185
|
-
conversationStore
|
|
186
|
-
});
|
|
187
|
-
if (!routing) throw new Error(`Conversation ${params.conversationId} is missing durable routing metadata`);
|
|
188
|
-
const source = record.source ?? routing.source;
|
|
189
|
-
if (!source) throw new Error("Completed plugin task session record is missing Source");
|
|
190
|
-
const conversation = await conversationStore.get({ conversationId: params.conversationId });
|
|
191
|
-
const runActor = record.actor ?? record.actors[0] ?? (record.dispatchId ? (await getDispatchRecord(record.dispatchId))?.actor : void 0);
|
|
192
|
-
const actorUser = runActor ? (await readActorIdentity(runActor))?.user : void 0;
|
|
193
|
-
const runEntries = turnMessagesWithProvenance(record).map(({ message, provenance }) => runTranscriptEntry(message, provenance, runActor)).filter((entry) => Boolean(entry));
|
|
194
|
-
const runMessageTexts = new Set(runEntries.filter((entry) => entry.type === "message").map((entry) => entry.text));
|
|
195
|
-
const contextEntries = (await loadConversationContextTranscriptEntries(record, conversation?.location, conversation?.visibility, runActor)).filter((entry) => entry.type !== "message" || !runMessageTexts.has(entry.text));
|
|
196
|
-
return pluginRunContextSchema.parse({
|
|
197
|
-
...actorUser ? { actorUserId: actorUser.id } : void 0,
|
|
198
|
-
completedAtMs: record.updatedAtMs,
|
|
199
|
-
conversationId: record.conversationId,
|
|
200
|
-
destination: routing.destination,
|
|
201
|
-
...routing.location ? { locationId: routing.location.id } : void 0,
|
|
202
|
-
actors: record.actors,
|
|
203
|
-
...runActor ? { actor: runActor } : void 0,
|
|
204
|
-
runId: record.turnId,
|
|
205
|
-
source,
|
|
206
|
-
transcript: [...contextEntries, ...runEntries]
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
/** Build the plugin-facing context for one claimed task attempt. */
|
|
210
|
-
function taskPluginContext(plugin, message, options = {}) {
|
|
211
|
-
const pluginName = plugin.manifest.name;
|
|
212
|
-
const sessionParams = pluginTaskParamsSchema.parse(message.params);
|
|
213
|
-
const onCost = createPluginModelCostRecorder({
|
|
214
|
-
conversationId: sessionParams.conversationId,
|
|
215
|
-
pluginName,
|
|
216
|
-
source: "task",
|
|
217
|
-
turnId: sessionParams.sessionId
|
|
218
|
-
});
|
|
219
|
-
return {
|
|
220
|
-
db: getDb(),
|
|
221
|
-
embedder: createPluginEmbedder(pluginName, {
|
|
222
|
-
onCost,
|
|
223
|
-
signal: options.signal
|
|
224
|
-
}),
|
|
225
|
-
events: createPluginConversationEvents({
|
|
226
|
-
conversationId: sessionParams.conversationId,
|
|
227
|
-
operationId: pluginTaskId(message),
|
|
228
|
-
plugin,
|
|
229
|
-
turnId: sessionParams.sessionId
|
|
230
|
-
}),
|
|
231
|
-
id: pluginTaskId(message),
|
|
232
|
-
log: createPluginLogger(pluginName),
|
|
233
|
-
model: createPluginModel(pluginName, plugin.model, {
|
|
234
|
-
onCost,
|
|
235
|
-
signal: options.signal
|
|
236
|
-
}),
|
|
237
|
-
name: message.name,
|
|
238
|
-
plugin: { name: pluginName },
|
|
239
|
-
cache: createPluginCache(pluginName),
|
|
240
|
-
run: { async load() {
|
|
241
|
-
return await loadPluginRun(sessionParams);
|
|
242
|
-
} },
|
|
243
|
-
state: createPluginState(pluginName)
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
function findPluginTask(message) {
|
|
247
|
-
const plugin = [...coreTaskRegistrations(), ...getPlugins()].find((candidate) => candidate.manifest.name === message.plugin);
|
|
248
|
-
if (!plugin?.tasks || !Object.hasOwn(plugin.tasks, message.name)) return;
|
|
249
|
-
return {
|
|
250
|
-
plugin,
|
|
251
|
-
task: plugin.tasks[message.name]
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
/** Schedule all plugin tasks interested in a completed agent-run session. */
|
|
255
|
-
async function scheduleSessionCompletedPluginTasks(params, options = {}) {
|
|
256
|
-
const coreParams = pluginTaskParamsSchema.parse(params);
|
|
257
|
-
const taskRegistrations = [...getPlugins(), ...coreTaskRegistrations()].flatMap((plugin) => Object.keys(plugin.tasks ?? {}).map((name) => ({
|
|
258
|
-
name,
|
|
259
|
-
plugin
|
|
260
|
-
})));
|
|
261
|
-
if (taskRegistrations.length === 0) return;
|
|
262
|
-
const record = await getTurnRecord(coreParams.conversationId, coreParams.sessionId);
|
|
263
|
-
if (!record || record.state !== "completed") throw new Error("Completed plugin task session record is not ready");
|
|
264
|
-
const send = options.send ?? sendVercelPluginTask;
|
|
265
|
-
const messages = taskRegistrations.map(({ name, plugin }) => ({
|
|
266
|
-
name,
|
|
267
|
-
params: coreParams,
|
|
268
|
-
plugin: plugin.manifest.name
|
|
269
|
-
}));
|
|
270
|
-
await Promise.all(messages.map(async (message) => {
|
|
271
|
-
await send(message);
|
|
272
|
-
}));
|
|
273
|
-
}
|
|
274
|
-
/**
|
|
275
|
-
* Execute one parsed plugin task request in a `plugin.task` span. The span
|
|
276
|
-
* includes the lock wait, because both delay the work that runs the task.
|
|
277
|
-
*/
|
|
278
|
-
async function processPluginTask(message, options = {}) {
|
|
279
|
-
const params = pluginTaskParamsSchema.parse(message.params);
|
|
280
|
-
await withSpan(`plugin.task ${message.plugin}.${message.name}`, "plugin.task", { conversationId: params.conversationId }, () => withPluginTaskLock(pluginTaskId(message), async () => {
|
|
281
|
-
const resolved = findPluginTask(message);
|
|
282
|
-
if (!resolved?.task) throw new Error(`Plugin task "${message.plugin}.${message.name}" is not registered`);
|
|
283
|
-
await resolved.task.run(taskPluginContext(resolved.plugin, message, options));
|
|
284
|
-
}), {
|
|
285
|
-
"app.ai.turn.session_id": params.sessionId,
|
|
286
|
-
"app.plugin.name": message.plugin,
|
|
287
|
-
"app.plugin.task": message.name
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
export { scheduleSessionCompletedPluginTasks as n, task_runner_exports as r, processPluginTask as t };
|
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
import { Kr as JUNIOR_THREAD_STATE_TTL_MS, wo as createDurableLocationConfigurationService, y as persistConversationMessages } from "./projection-0UcUeuzn.js";
|
|
2
|
-
import { G as toOptionalNumber, K as toOptionalString, W as isRecord } from "./logging-Qo-7xGp1.js";
|
|
3
|
-
import { S as getDb } from "./viewer-BlpnzZZa.js";
|
|
4
|
-
import { r as getStateAdapter } from "./adapter-CW5UW7vL.js";
|
|
5
|
-
// src/chat/state/conversation.ts
|
|
6
|
-
function defaultConversationState() {
|
|
7
|
-
return {
|
|
8
|
-
schemaVersion: 1,
|
|
9
|
-
messages: [],
|
|
10
|
-
compactions: [],
|
|
11
|
-
processing: {},
|
|
12
|
-
vision: { byFileId: {} }
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
function coercePendingAuthState(value) {
|
|
16
|
-
if (!isRecord(value)) return;
|
|
17
|
-
const kind = value.kind;
|
|
18
|
-
const provider = toOptionalString(value.provider);
|
|
19
|
-
const actorId = toOptionalString(value.actorId);
|
|
20
|
-
const authSessionId = toOptionalString(value.authSessionId);
|
|
21
|
-
const scope = toOptionalString(value.scope);
|
|
22
|
-
const sessionId = toOptionalString(value.sessionId);
|
|
23
|
-
const linkSentAtMs = toOptionalNumber(value.linkSentAtMs);
|
|
24
|
-
if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
|
|
25
|
-
const base = {
|
|
26
|
-
provider,
|
|
27
|
-
actorId,
|
|
28
|
-
...scope ? { scope } : void 0,
|
|
29
|
-
sessionId,
|
|
30
|
-
linkSentAtMs
|
|
31
|
-
};
|
|
32
|
-
return kind === "mcp" ? {
|
|
33
|
-
...base,
|
|
34
|
-
authSessionId,
|
|
35
|
-
kind
|
|
36
|
-
} : {
|
|
37
|
-
...base,
|
|
38
|
-
kind
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
/** Safely coerce an unknown persisted value into a ThreadConversationState. */
|
|
42
|
-
function coerceThreadConversationState(value) {
|
|
43
|
-
if (!isRecord(value)) return defaultConversationState();
|
|
44
|
-
const root = value;
|
|
45
|
-
const rawConversation = isRecord(root.conversation) ? root.conversation : {};
|
|
46
|
-
const messages = [];
|
|
47
|
-
const compactions = [];
|
|
48
|
-
const rawProcessing = isRecord(rawConversation.processing) ? rawConversation.processing : {};
|
|
49
|
-
const processing = {
|
|
50
|
-
activeTurnId: toOptionalString(rawProcessing.activeTurnId),
|
|
51
|
-
lastCompletedAtMs: toOptionalNumber(rawProcessing.lastCompletedAtMs),
|
|
52
|
-
pendingAuth: coercePendingAuthState(rawProcessing.pendingAuth)
|
|
53
|
-
};
|
|
54
|
-
const rawVision = isRecord(rawConversation.vision) ? rawConversation.vision : {};
|
|
55
|
-
const rawVisionByFileId = isRecord(rawVision.byFileId) ? rawVision.byFileId : {};
|
|
56
|
-
const byFileId = {};
|
|
57
|
-
for (const [fileId, value] of Object.entries(rawVisionByFileId)) {
|
|
58
|
-
if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
|
|
59
|
-
if (!isRecord(value)) continue;
|
|
60
|
-
const summary = toOptionalString(value.summary);
|
|
61
|
-
const analyzedAtMs = toOptionalNumber(value.analyzedAtMs);
|
|
62
|
-
if (!summary || !analyzedAtMs) continue;
|
|
63
|
-
byFileId[fileId] = {
|
|
64
|
-
summary,
|
|
65
|
-
analyzedAtMs
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
return {
|
|
69
|
-
schemaVersion: 1,
|
|
70
|
-
messages,
|
|
71
|
-
compactions,
|
|
72
|
-
processing,
|
|
73
|
-
vision: {
|
|
74
|
-
backfillCompletedAtMs: toOptionalNumber(rawVision.backfillCompletedAtMs),
|
|
75
|
-
byFileId
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Wrap active conversation control into the thread scratch envelope.
|
|
81
|
-
*
|
|
82
|
-
* Visible history lives in SQL. Image summaries use a separate disposable
|
|
83
|
-
* cache, so thread scratch does not retain them.
|
|
84
|
-
*/
|
|
85
|
-
function buildConversationStatePatch(conversation) {
|
|
86
|
-
return { conversation: {
|
|
87
|
-
schemaVersion: 1,
|
|
88
|
-
processing: { ...conversation.processing }
|
|
89
|
-
} };
|
|
90
|
-
}
|
|
91
|
-
// src/chat/runtime/thread-state.ts
|
|
92
|
-
function threadStateKey(threadId) {
|
|
93
|
-
return `thread-state:${threadId}`;
|
|
94
|
-
}
|
|
95
|
-
function channelStateKey(channelId) {
|
|
96
|
-
return `channel-state:${channelId}`;
|
|
97
|
-
}
|
|
98
|
-
function buildThreadStatePayload(patch) {
|
|
99
|
-
const payload = {};
|
|
100
|
-
if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
|
|
101
|
-
if (patch.sandboxRef !== void 0) {
|
|
102
|
-
payload.app_sandbox_id = patch.sandboxRef?.id ?? "";
|
|
103
|
-
payload.app_sandbox_dependency_profile_hash = patch.sandboxRef?.profileHash ?? "";
|
|
104
|
-
payload.app_sandbox_workspace_id = patch.sandboxRef?.workspaceId ?? "";
|
|
105
|
-
}
|
|
106
|
-
return payload;
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Merge a payload into thread scratch with Junior's TTL.
|
|
110
|
-
*
|
|
111
|
-
* Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
|
|
112
|
-
* shorter retention policy for the same scratch keys.
|
|
113
|
-
*/
|
|
114
|
-
async function mergePersistedState(key, payload) {
|
|
115
|
-
if (Object.keys(payload).length === 0) return;
|
|
116
|
-
const stateAdapter = getStateAdapter();
|
|
117
|
-
await stateAdapter.connect();
|
|
118
|
-
const existing = await stateAdapter.get(key) ?? {};
|
|
119
|
-
await stateAdapter.set(key, {
|
|
120
|
-
...existing,
|
|
121
|
-
...payload
|
|
122
|
-
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
123
|
-
}
|
|
124
|
-
/** Extract persisted sandbox metadata from thread state payload. */
|
|
125
|
-
function getPersistedSandboxState(state) {
|
|
126
|
-
const id = toOptionalString(state.app_sandbox_id);
|
|
127
|
-
if (!id) return;
|
|
128
|
-
const profileHash = toOptionalString(state.app_sandbox_dependency_profile_hash);
|
|
129
|
-
const workspaceId = toOptionalString(state.app_sandbox_workspace_id);
|
|
130
|
-
return {
|
|
131
|
-
id,
|
|
132
|
-
...profileHash ? { profileHash } : void 0,
|
|
133
|
-
...workspaceId ? { workspaceId } : void 0
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
/** Persist only the Redis-backed runtime scratch in a thread-state patch. */
|
|
137
|
-
async function persistThreadRuntimeState(conversationId, patch) {
|
|
138
|
-
await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
|
|
139
|
-
}
|
|
140
|
-
/** Load the persisted state payload for a thread without requiring a Chat singleton. */
|
|
141
|
-
async function getPersistedThreadState(threadId) {
|
|
142
|
-
const stateAdapter = getStateAdapter();
|
|
143
|
-
await stateAdapter.connect();
|
|
144
|
-
return await stateAdapter.get(threadStateKey(threadId)) ?? {};
|
|
145
|
-
}
|
|
146
|
-
/** Persist a thread-state patch by thread id without constructing a Chat thread. */
|
|
147
|
-
async function persistThreadStateById(threadId, patch) {
|
|
148
|
-
if (patch.conversation) await persistConversationMessages({
|
|
149
|
-
conversation: patch.conversation,
|
|
150
|
-
conversationId: threadId
|
|
151
|
-
});
|
|
152
|
-
await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
|
|
153
|
-
}
|
|
154
|
-
/** Load legacy Redis-backed channel state during the SQL cutover. */
|
|
155
|
-
async function getLegacyChannelState(channelId) {
|
|
156
|
-
const stateAdapter = getStateAdapter();
|
|
157
|
-
await stateAdapter.connect();
|
|
158
|
-
return await stateAdapter.get(channelStateKey(channelId)) ?? {};
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Resolve durable location configuration.
|
|
162
|
-
*
|
|
163
|
-
* Slack still reads the old channel-id Redis bag once during cutover.
|
|
164
|
-
*/
|
|
165
|
-
function getLocationConfigurationService(destination) {
|
|
166
|
-
if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
|
|
167
|
-
return createDurableLocationConfigurationService({
|
|
168
|
-
destination,
|
|
169
|
-
db: getDb(),
|
|
170
|
-
loadLegacy: async () => await getLegacyChannelState(destination.channelId)
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
export { persistThreadStateById as a, persistThreadRuntimeState as i, getPersistedSandboxState as n, coerceThreadConversationState as o, getPersistedThreadState as r, getLocationConfigurationService as t };
|