@sentry/junior 0.296.0 → 0.298.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/{admin-z_lgDi-z.js → admin-BF3DbYGf.js} +2 -2
- package/dist/{agent-runner-HoQiUKLL.js → agent-runner-Q9GkoerG.js} +407 -1895
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +38 -267
- package/dist/{app-C75Ft-A_.d.ts → app-DOg_mCtV.d.ts} +7 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +64 -44
- package/dist/attempt-selection-ClP3MMPr.js +61 -0
- package/dist/{automation-yJX3C7i3.js → automation-Cn8qmbdr.js} +1 -1
- package/dist/{background-compaction-queue-Cre1wFt9.js → background-compaction-queue-BZhGFOK6.js} +4 -88
- package/dist/{briefs-BXECHduJ.js → briefs-CQrCRF6-.js} +3 -3
- package/dist/{catalog-runtime-CpCmlD9L.js → catalog-runtime-DZeD2WbL.js} +1 -1
- package/dist/cli/chat.js +19 -15
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-CCPHvTqx.js → config-BOByVnxe.js} +2 -2
- package/dist/{connections-B5pWh8e2.js → connections-BNN5cJam.js} +6 -6
- package/dist/{conversation-CMkSmi02.js → conversation-DCkzvxqB.js} +51 -17
- package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-CMA12Rjs.js} +1 -1
- package/dist/{conversation-privacy-CZD5soDW.js → conversation-privacy-C0eRxsgb.js} +1 -1
- package/dist/conversation-turn-D9qvcDX6.js +805 -0
- package/dist/{credential-sync-DwLkIvXI.js → credential-sync-B_iUpxGL.js} +14 -13
- package/dist/{db-C1M1y-bh.js → db-CoMNr2Zm.js} +43 -15
- package/dist/{db-B3iyr_Or.d.ts → db-DoMcnYol.d.ts} +13 -1
- package/dist/{executor-DUSEwXaO.js → executor-C-m8VrzX.js} +14 -6
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-D0svFM8r.js → logging-CJTi5niy.js} +1 -1
- package/dist/{message-BFnIwKpx.js → message-Q6_5DAWR.js} +15 -13
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -2
- package/dist/{session-stop-hYNTNpVf.js → notification-Bv25xbj0.js} +11 -930
- package/dist/{oauth-callback-server-BXRtD6Fk.js → oauth-callback-server-CH5XAyo-.js} +2 -2
- package/dist/{projection-B6VS7kbo.js → projection-BgwEE36_.js} +333 -106
- package/dist/{prompt-CD11tfG8.js → prompt-DXc9DYT9.js} +4 -4
- package/dist/prompt-input-BUr4J9RO.js +1424 -0
- package/dist/{registry-CHewwYEo.js → registry-9XwqSnM-.js} +1 -1
- package/dist/reporting-window-DopzcOHh.js +137 -0
- package/dist/{resolve-1owMH4qo.js → resolve-DUIAbcRL.js} +3 -3
- package/dist/result-C2Vn8QGn.js +463 -0
- package/dist/{runner-BtWvJslp.js → runner-CXGtw-Mc.js} +9 -8
- package/dist/{sandbox-egress-signals-ByftwJVt.js → sandbox-egress-signals-Di3S_dO7.js} +1 -1
- package/dist/{schema-Ct1Zf2xy.d.ts → schema-BnbZ-rKv.d.ts} +14 -107
- package/dist/{schema-D2iGyYIp.js → schema-Dyp7racy.js} +11 -48
- package/dist/{service-account-BZEuMKdo.js → service-account-DM3KBBeG.js} +3 -3
- package/dist/{service-account-DLoeoHww.js → service-account-GzAMUQ8a.js} +3 -3
- package/dist/session-stop-D4i7e6iT.js +181 -0
- package/dist/{skills-DXgd5Inh.js → skills-DCK9SD_l.js} +2 -2
- package/dist/{spawn-YeqlNDv8.js → spawn-6cX6xE9G.js} +6 -5
- package/dist/{state-C3CbtD_m.js → state-CSuA2J1V.js} +2 -2
- package/dist/{stop-Cze_pEL8.js → stop-Dh2DfwpK.js} +66 -159
- package/dist/{store-CZ9vqR4P.js → store-B1zepKG8.js} +11 -4
- package/dist/{task-runner-CMiNGsER.js → store-DrA17Fbz.js} +939 -1593
- package/dist/task-queue-D1rXWfFN.js +89 -0
- package/dist/task-runner-CT4M8oDz.js +291 -0
- package/dist/thread-context-DnqUkbzN.js +248 -0
- package/dist/turn-cancel-l460pfGW.js +201 -0
- package/dist/turn-session-routing-VXDVXLRl.js +380 -0
- package/dist/{turn-failure-response-pXhZ2wMK.js → turn-user-message-BSPmkm7X.js} +181 -392
- package/dist/turn-wake-DVFVXyhX.js +161 -0
- package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
- package/dist/{validation-Du7NdkOR.js → validation-zxAJBDDy.js} +1 -1
- package/dist/{version-EN3Wnq-R.js → version-DcZ40a0g.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-Agxi_o5c.js → viewer-CgiGjW10.js} +3 -3
- package/dist/warmup-CwKbxQLl.js +2698 -0
- package/dist/{worker-BALVdWbv.js → worker-CbDUzaBA.js} +20 -8
- package/migrations/0102_code_change_last_activity.sql +1 -0
- package/migrations/0103_agent_invocation_fork.sql +8 -0
- package/migrations/meta/0102_snapshot.json +4502 -0
- package/migrations/meta/0103_snapshot.json +4509 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +4 -4
- package/dist/result-CEqQFrEf.js +0 -305
- package/dist/result-event-type-DD6BAgT7.js +0 -11
- package/dist/warmup-CY2ArYag.js +0 -2017
- package/dist/work-EA98F0ia.js +0 -768
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { X as clearPendingAuth, j as markConversationMessage, ot as getTurnRecord, rt as abandonTurnRecord, v as hydrateConversationMessages } from "./projection-BgwEE36_.js";
|
|
2
|
+
import { r as getConversationEventStore } from "./db-CoMNr2Zm.js";
|
|
3
|
+
import { g as getAuthPausedConversationTurnId, v as listActiveMailboxTurns } from "./prompt-input-BUr4J9RO.js";
|
|
4
|
+
import { _ as ConversationTurnLifecycleService, p as markTurnClosed, t as getTurnUserMessage } from "./turn-user-message-BSPmkm7X.js";
|
|
5
|
+
import { a as getPersistedThreadState, c as coerceThreadConversationState, s as persistThreadStateById } from "./turn-session-routing-VXDVXLRl.js";
|
|
6
|
+
import { n as getPausedTurnRequest, s as deleteWebAuthorization } from "./turn-wake-DVFVXyhX.js";
|
|
7
|
+
import { t as canJoinTurn } from "./attempt-selection-ClP3MMPr.js";
|
|
8
|
+
// src/chat/runtime/turn-execution.ts
|
|
9
|
+
/** An error thrown while the agent advances a Run. */
|
|
10
|
+
var AgentRunError = class extends Error {
|
|
11
|
+
constructor(cause) {
|
|
12
|
+
super(cause instanceof Error ? cause.message : "Agent Run failed", { cause });
|
|
13
|
+
this.name = "AgentRunError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Run the agent and finish the Turn after the caller saves its result.
|
|
18
|
+
*
|
|
19
|
+
* A paused Run, or a Run waiting for authorization, leaves the Turn open. A
|
|
20
|
+
* save error also leaves the Turn open so the worker can retry or recover it.
|
|
21
|
+
*/
|
|
22
|
+
async function executeTurn(agentRunner, run, saveResult) {
|
|
23
|
+
let outcome;
|
|
24
|
+
try {
|
|
25
|
+
outcome = await agentRunner.run(run);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
throw new AgentRunError(error);
|
|
28
|
+
}
|
|
29
|
+
if (outcome.status !== "completed") return outcome;
|
|
30
|
+
const saved = await saveResult(outcome.result);
|
|
31
|
+
await finishTurn(run.conversationId, run.turnId, saved);
|
|
32
|
+
return { status: "completed" };
|
|
33
|
+
}
|
|
34
|
+
/** Record the terminal lifecycle event of a Turn from its saved result. */
|
|
35
|
+
async function finishTurn(conversationId, turnId, saved) {
|
|
36
|
+
const lifecycle = new ConversationTurnLifecycleService(getConversationEventStore());
|
|
37
|
+
const common = {
|
|
38
|
+
conversationId,
|
|
39
|
+
createdAtMs: saved.finishedAtMs ?? Date.now(),
|
|
40
|
+
turnId
|
|
41
|
+
};
|
|
42
|
+
if (saved.outcome === "failed") await lifecycle.fail({
|
|
43
|
+
...common,
|
|
44
|
+
...saved.eventId ? { eventId: saved.eventId } : void 0,
|
|
45
|
+
failureCode: saved.failureCode,
|
|
46
|
+
...saved.failureReason ? { failureReason: saved.failureReason } : void 0
|
|
47
|
+
});
|
|
48
|
+
else await lifecycle.complete({
|
|
49
|
+
...common,
|
|
50
|
+
outcome: saved.outcome
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
// src/chat/task-execution/supersede-turns.ts
|
|
54
|
+
/**
|
|
55
|
+
* End every open mailbox Turn other than `keepTurnId`, so new input runs in
|
|
56
|
+
* the only open Turn. New input starts only when no yielded Turn waits, so an
|
|
57
|
+
* open Turn here waits for OAuth or was left open by a failed or stopped Run.
|
|
58
|
+
* The caller persists `conversation`. Returns false when `isStopped` turns
|
|
59
|
+
* true first.
|
|
60
|
+
*/
|
|
61
|
+
async function supersedeOpenMailboxTurns(args) {
|
|
62
|
+
return await supersedeTurns({
|
|
63
|
+
...args,
|
|
64
|
+
turns: (await listActiveMailboxTurns(args.conversationId)).filter((record) => record.turnId !== args.keepTurnId)
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* End open Turns that new input replaces. A late resume or OAuth callback
|
|
69
|
+
* for an ended Turn is a no-op. The caller persists `conversation`. Returns
|
|
70
|
+
* false when `isStopped` turns true first.
|
|
71
|
+
*/
|
|
72
|
+
async function supersedeTurns(args) {
|
|
73
|
+
const pendingAuthorizationActorId = args.conversation.processing.pendingAuth?.actorId;
|
|
74
|
+
for (const stale of args.turns) {
|
|
75
|
+
if (args.isStopped?.()) return false;
|
|
76
|
+
await abandonTurnRecord({
|
|
77
|
+
conversationId: args.conversationId,
|
|
78
|
+
turnId: stale.turnId,
|
|
79
|
+
errorMessage: "Turn superseded by new input"
|
|
80
|
+
});
|
|
81
|
+
await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
|
|
82
|
+
conversationId: args.conversationId,
|
|
83
|
+
createdAtMs: Date.now(),
|
|
84
|
+
outcome: "cancelled",
|
|
85
|
+
turnId: stale.turnId
|
|
86
|
+
});
|
|
87
|
+
markTurnClosed({
|
|
88
|
+
conversation: args.conversation,
|
|
89
|
+
nowMs: Date.now(),
|
|
90
|
+
sessionId: stale.turnId
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
if (args.turns.some((record) => record.state === "paused" && record.resumeReason === "auth") && pendingAuthorizationActorId) await deleteWebAuthorization({
|
|
94
|
+
actorId: pendingAuthorizationActorId,
|
|
95
|
+
conversationId: args.conversationId
|
|
96
|
+
});
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* End the Turn that waits for its next Run when `message` cannot join it, so
|
|
101
|
+
* the message starts its own Turn instead of running with that Turn's Actor.
|
|
102
|
+
* A stored legacy Turn without an Actor keeps taking the input.
|
|
103
|
+
*/
|
|
104
|
+
async function supersedeTurnForInput(args) {
|
|
105
|
+
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
106
|
+
const turnId = conversation.processing.activeTurnId;
|
|
107
|
+
if (!turnId || !await getPausedTurnRequest({
|
|
108
|
+
conversationId: args.conversationId,
|
|
109
|
+
turnId
|
|
110
|
+
})) return;
|
|
111
|
+
const turn = await getTurnRecord(args.conversationId, turnId);
|
|
112
|
+
if (!turn?.actor || canJoinTurn(turn, args.message)) return;
|
|
113
|
+
await hydrateConversationMessages({
|
|
114
|
+
conversation,
|
|
115
|
+
conversationId: args.conversationId
|
|
116
|
+
});
|
|
117
|
+
await supersedeTurns({
|
|
118
|
+
conversation,
|
|
119
|
+
conversationId: args.conversationId,
|
|
120
|
+
turns: [turn]
|
|
121
|
+
});
|
|
122
|
+
await persistThreadStateById(args.conversationId, { conversation });
|
|
123
|
+
}
|
|
124
|
+
// src/chat/task-execution/turn-cancel.ts
|
|
125
|
+
/**
|
|
126
|
+
* End a cancelled Turn: a stop that a worker saw, or a stop of a Turn that
|
|
127
|
+
* waits for sign-in with no worker.
|
|
128
|
+
*/
|
|
129
|
+
/** Close a cancelled Turn, save it, and acknowledge its input. */
|
|
130
|
+
async function completeCancelledConversationTurn(args) {
|
|
131
|
+
const pendingAuthorization = args.conversation.processing.pendingAuth?.sessionId === args.turnId ? args.conversation.processing.pendingAuth : void 0;
|
|
132
|
+
await abandonTurnRecord({
|
|
133
|
+
conversationId: args.conversationId,
|
|
134
|
+
turnId: args.turnId,
|
|
135
|
+
errorMessage: "Turn cancelled"
|
|
136
|
+
});
|
|
137
|
+
clearPendingAuth(args.conversation, args.turnId);
|
|
138
|
+
markConversationMessage(args.conversation, args.userMessageId, {
|
|
139
|
+
replied: false,
|
|
140
|
+
skippedReason: "turn cancelled"
|
|
141
|
+
});
|
|
142
|
+
markTurnClosed({
|
|
143
|
+
conversation: args.conversation,
|
|
144
|
+
nowMs: Date.now(),
|
|
145
|
+
sessionId: args.turnId
|
|
146
|
+
});
|
|
147
|
+
if (pendingAuthorization) await deleteWebAuthorization({
|
|
148
|
+
actorId: pendingAuthorization.actorId,
|
|
149
|
+
conversationId: args.conversationId
|
|
150
|
+
});
|
|
151
|
+
await persistThreadStateById(args.conversationId, {
|
|
152
|
+
conversation: args.conversation,
|
|
153
|
+
sandboxRef: args.sandboxRef
|
|
154
|
+
});
|
|
155
|
+
await new ConversationTurnLifecycleService(getConversationEventStore()).complete({
|
|
156
|
+
conversationId: args.conversationId,
|
|
157
|
+
createdAtMs: Date.now(),
|
|
158
|
+
outcome: "cancelled",
|
|
159
|
+
turnId: args.turnId
|
|
160
|
+
});
|
|
161
|
+
await args.acknowledge();
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* End the Turn of a stopped Conversation that waits for sign-in, so a later
|
|
165
|
+
* sign-in cannot resume it. A web Turn waits as an auth-paused Turn record. A
|
|
166
|
+
* Slack request waits as the thread's pending sign-in. Every stop path calls
|
|
167
|
+
* this, because no worker holds a waiting Turn and the stop wake can go to
|
|
168
|
+
* queued input first.
|
|
169
|
+
*/
|
|
170
|
+
async function cancelSignInWait(conversationId) {
|
|
171
|
+
const turnId = await getAuthPausedConversationTurnId(conversationId) ?? coerceThreadConversationState(await getPersistedThreadState(conversationId)).processing.pendingAuth?.sessionId;
|
|
172
|
+
if (turnId) await cancelSignInPausedTurn({
|
|
173
|
+
conversationId,
|
|
174
|
+
turnId
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Cancel a Turn that waits for sign-in outside its worker, with the same
|
|
179
|
+
* cleanup as a stopped resume.
|
|
180
|
+
*/
|
|
181
|
+
async function cancelSignInPausedTurn(args) {
|
|
182
|
+
if (!await abandonTurnRecord({
|
|
183
|
+
conversationId: args.conversationId,
|
|
184
|
+
errorMessage: "Turn cancelled",
|
|
185
|
+
onlyIfAuthPaused: true,
|
|
186
|
+
turnId: args.turnId
|
|
187
|
+
})) return;
|
|
188
|
+
const conversation = coerceThreadConversationState(await getPersistedThreadState(args.conversationId));
|
|
189
|
+
await hydrateConversationMessages({
|
|
190
|
+
conversation,
|
|
191
|
+
conversationId: args.conversationId
|
|
192
|
+
});
|
|
193
|
+
await completeCancelledConversationTurn({
|
|
194
|
+
acknowledge: async () => {},
|
|
195
|
+
conversation,
|
|
196
|
+
conversationId: args.conversationId,
|
|
197
|
+
turnId: args.turnId,
|
|
198
|
+
userMessageId: getTurnUserMessage(conversation, args.turnId)?.id
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
export { AgentRunError as a, supersedeTurnForInput as i, completeCancelledConversationTurn as n, executeTurn as o, supersedeOpenMailboxTurns as r, finishTurn as s, cancelSignInWait as t };
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { Ei as ToolInputError, Qo as createDurableLocationConfigurationService, b as persistConversationMessages, vi as JUNIOR_THREAD_STATE_TTL_MS } from "./projection-BgwEE36_.js";
|
|
2
|
+
import { G as isRecord, K as toOptionalNumber, q as toOptionalString } from "./logging-CJTi5niy.js";
|
|
3
|
+
import { o as getDb } from "./db-CoMNr2Zm.js";
|
|
4
|
+
import { a as getStateAdapter } from "./state-CSuA2J1V.js";
|
|
5
|
+
import * as z from "zod";
|
|
6
|
+
import { agentEventMatchSchema, anyResourceMatchFields, describeEventTrigger, eventTriggerChoices, eventTriggerProblems, normalizeEventIdentifier, normalizeEventMatch } from "@sentry/junior-plugin-api";
|
|
7
|
+
// src/chat/events/catalog.ts
|
|
8
|
+
/** A source with nothing enabled, for a namespace that the catalog lacks. */
|
|
9
|
+
const NO_SOURCE = {
|
|
10
|
+
resourceTypes: [],
|
|
11
|
+
events: {},
|
|
12
|
+
anyResourceFields: {}
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Build one catalog entry. It merges the filters of every resource type here,
|
|
16
|
+
* once, so trigger checks for each event copy and each row do not merge them
|
|
17
|
+
* again.
|
|
18
|
+
*/
|
|
19
|
+
function eventCatalogEntry(registration) {
|
|
20
|
+
return {
|
|
21
|
+
...registration,
|
|
22
|
+
anyResourceFields: anyResourceMatchFields(registration.resourceTypes)
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** Core-owned event namespace. Not a plugin publisher. */
|
|
26
|
+
const CORE_EVENT_NAMESPACE = "junior";
|
|
27
|
+
/** True when the catalog has any enabled registration. */
|
|
28
|
+
function hasEventCatalogEntries(catalog) {
|
|
29
|
+
return Object.keys(catalog).length > 0;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Catalog entries that durable event automations may select.
|
|
33
|
+
*
|
|
34
|
+
* Resource types with `automation: false` stay out of create/update schemas
|
|
35
|
+
* and trigger availability. A namespace with no such resource type left is
|
|
36
|
+
* removed.
|
|
37
|
+
*/
|
|
38
|
+
function automationEventCatalog(catalog) {
|
|
39
|
+
return Object.fromEntries(Object.entries(catalog).flatMap(([namespace, registration]) => {
|
|
40
|
+
const resourceTypes = registration.resourceTypes.filter((resourceType) => registration.limits?.[resourceType.type]?.automation !== false);
|
|
41
|
+
if (resourceTypes.length === 0) return [];
|
|
42
|
+
if (resourceTypes.length === registration.resourceTypes.length) return [[namespace, registration]];
|
|
43
|
+
const supported = new Set(resourceTypes.flatMap((resourceType) => resourceType.supportedEvents));
|
|
44
|
+
return [[namespace, eventCatalogEntry({
|
|
45
|
+
...registration,
|
|
46
|
+
resourceTypes,
|
|
47
|
+
events: Object.fromEntries(Object.entries(registration.events).filter(([eventType]) => supported.has(eventType)))
|
|
48
|
+
})]];
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
/** Return why watchEvents cannot watch one resource type, if it cannot. */
|
|
52
|
+
function eventWatchUnavailable(catalog, namespace, resourceType) {
|
|
53
|
+
const limits = catalog[namespace]?.limits?.[resourceType];
|
|
54
|
+
return limits?.watch === false ? limits.watchUnavailableMessage : void 0;
|
|
55
|
+
}
|
|
56
|
+
function enumSchema(values, unavailableMessage) {
|
|
57
|
+
if (values.length === 0) return z.string().refine(() => false, unavailableMessage);
|
|
58
|
+
return z.enum(values);
|
|
59
|
+
}
|
|
60
|
+
/** Build the model-facing namespace enum from enabled event plugins. */
|
|
61
|
+
function eventNamespaceSchema(catalog) {
|
|
62
|
+
return enumSchema(Object.keys(catalog).sort(), "No event namespaces are enabled.");
|
|
63
|
+
}
|
|
64
|
+
/** Build the model-facing event enum from enabled plugin registrations. */
|
|
65
|
+
function registeredEventTypeSchema(catalog) {
|
|
66
|
+
return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.flatMap((resourceType) => resourceType.supportedEvents)))].sort(), "No event types are enabled.");
|
|
67
|
+
}
|
|
68
|
+
/** Build the model-facing resource type enum from enabled plugin registrations. */
|
|
69
|
+
function registeredResourceTypeSchema(catalog) {
|
|
70
|
+
return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.map((resourceType) => resourceType.type)))].sort(), "No resource types are enabled.");
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Return app guidance for one event of a namespace. The source declares it
|
|
74
|
+
* once for the event, so every resource type and a trigger with no resource
|
|
75
|
+
* type get the same guidance.
|
|
76
|
+
*/
|
|
77
|
+
function eventGuidance(catalog, namespace, eventType) {
|
|
78
|
+
return catalog[namespace]?.events[eventType]?.guidance;
|
|
79
|
+
}
|
|
80
|
+
/** Build the match object the tools accept for one resource type. */
|
|
81
|
+
function registeredEventMatchSchema() {
|
|
82
|
+
return agentEventMatchSchema.optional().describe("Optional filters: exact values for the resource type match_fields, with snake_case keys. A single value must equal the event data. A list means the event value may be any one entry. For a field with list: true, the event value is a list, and it matches when it includes the value or any entry. A field with events is set only on those events, so every selected event must be in that list. Omit a key to ignore it. Unmatched events are dropped with no agent turn.");
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* List why a selection cannot work with the enabled plugins. Use it for new
|
|
86
|
+
* selections and for saved triggers, which can go stale after a plugin renames
|
|
87
|
+
* or removes a resource type, event, or filter.
|
|
88
|
+
*/
|
|
89
|
+
function registeredEventTriggerProblems(catalog, selection, options) {
|
|
90
|
+
return eventTriggerProblems(catalog[selection.namespace] ?? NO_SOURCE, selection, options);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Describe a selection with the enabled plugins, for the dashboard and Slack.
|
|
94
|
+
* Its problems are the same as `registeredEventTriggerProblems`.
|
|
95
|
+
*/
|
|
96
|
+
function describeRegisteredEventTrigger(catalog, selection) {
|
|
97
|
+
return describeEventTrigger(catalog[selection.namespace] ?? NO_SOURCE, selection);
|
|
98
|
+
}
|
|
99
|
+
function uniqueMatchValues(match) {
|
|
100
|
+
if (!match || Object.keys(match).length === 0) return void 0;
|
|
101
|
+
return Object.fromEntries(Object.entries(match).map(([key, value]) => [key, Array.isArray(value) ? [...new Set(value)] : value]));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Reject an event automation trigger or a Watch that cannot work, with every
|
|
105
|
+
* problem in one message for the agent. Return its match as it is saved:
|
|
106
|
+
* each text value in the case that its plugin declares, with no repeated
|
|
107
|
+
* list values. The dashboard clears `inputKeys` so messages name the filters
|
|
108
|
+
* as its plugin declares them.
|
|
109
|
+
*/
|
|
110
|
+
function requireValidEventTrigger(catalog, selection, target, options = { inputKeys: true }) {
|
|
111
|
+
const fields = eventTriggerChoices(catalog[selection.namespace] ?? NO_SOURCE, selection)?.fields ?? {};
|
|
112
|
+
const normalized = {
|
|
113
|
+
...selection,
|
|
114
|
+
match: normalizeEventMatch(fields, selection.match)
|
|
115
|
+
};
|
|
116
|
+
const problems = registeredEventTriggerProblems(catalog, normalized, options);
|
|
117
|
+
if (problems.length > 0) {
|
|
118
|
+
const source = catalog[selection.namespace]?.displayName ?? selection.namespace;
|
|
119
|
+
const resource = selection.resourceType ? `${source} ${selection.resourceType.replaceAll("_", " ")}` : source;
|
|
120
|
+
throw new ToolInputError([target === "watch" ? `This ${resource} watch cannot be created.` : `This ${resource} trigger cannot be saved.`, ...problems.map((problem) => problem.message)].join(" "));
|
|
121
|
+
}
|
|
122
|
+
return uniqueMatchValues(normalized.match);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Normalize one selector with the convention declared by its plugin.
|
|
126
|
+
*
|
|
127
|
+
* Reject a selector that does not fit its resource type. Resource types can
|
|
128
|
+
* share event types, so only the identifier shows which one a selector names.
|
|
129
|
+
*/
|
|
130
|
+
function requireEventIdentifier(catalog, input) {
|
|
131
|
+
const registration = catalog[input.namespace];
|
|
132
|
+
const identifier = normalizeEventIdentifier(registration, input.identifier);
|
|
133
|
+
const resourceTypes = registration?.resourceTypes ?? [];
|
|
134
|
+
const fits = (resourceType) => resourceType.identifier !== void 0 && new RegExp(resourceType.identifier.pattern).test(identifier);
|
|
135
|
+
const resourceType = resourceTypes.find((candidate) => candidate.type === input.resourceType);
|
|
136
|
+
if (!resourceType?.identifier || fits(resourceType)) return identifier;
|
|
137
|
+
const fitting = resourceTypes.filter(fits).map((candidate) => candidate.type);
|
|
138
|
+
throw new ToolInputError([`Identifier "${identifier}" does not fit resource_type "${input.resourceType}" in namespace "${input.namespace}". Expected format: "${resourceType.identifier.format}".`, ...fitting.length > 0 ? [`If the identifier is correct, use one of these resource_type values: ${fitting.map((type) => `"${type}"`).join(", ")}.`] : []].join(" "));
|
|
139
|
+
}
|
|
140
|
+
// src/chat/state/conversation.ts
|
|
141
|
+
function defaultConversationState() {
|
|
142
|
+
return {
|
|
143
|
+
schemaVersion: 1,
|
|
144
|
+
messages: [],
|
|
145
|
+
processing: {},
|
|
146
|
+
vision: { byFileId: {} }
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function coercePendingAuthState(value) {
|
|
150
|
+
if (!isRecord(value)) return;
|
|
151
|
+
const kind = value.kind;
|
|
152
|
+
const provider = toOptionalString(value.provider);
|
|
153
|
+
const actorId = toOptionalString(value.actorId);
|
|
154
|
+
const authSessionId = toOptionalString(value.authSessionId);
|
|
155
|
+
const scope = toOptionalString(value.scope);
|
|
156
|
+
const sessionId = toOptionalString(value.sessionId);
|
|
157
|
+
const linkSentAtMs = toOptionalNumber(value.linkSentAtMs);
|
|
158
|
+
if (kind !== "mcp" && kind !== "plugin" || !provider || !actorId || kind === "mcp" && !authSessionId || !sessionId || typeof linkSentAtMs !== "number") return;
|
|
159
|
+
const base = {
|
|
160
|
+
provider,
|
|
161
|
+
actorId,
|
|
162
|
+
...scope ? { scope } : void 0,
|
|
163
|
+
sessionId,
|
|
164
|
+
linkSentAtMs
|
|
165
|
+
};
|
|
166
|
+
return kind === "mcp" ? {
|
|
167
|
+
...base,
|
|
168
|
+
authSessionId,
|
|
169
|
+
kind
|
|
170
|
+
} : {
|
|
171
|
+
...base,
|
|
172
|
+
kind
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/** Safely coerce an unknown persisted value into a ThreadConversationState. */
|
|
176
|
+
function coerceThreadConversationState(value) {
|
|
177
|
+
if (!isRecord(value)) return defaultConversationState();
|
|
178
|
+
const root = value;
|
|
179
|
+
const rawConversation = isRecord(root.conversation) ? root.conversation : {};
|
|
180
|
+
const messages = [];
|
|
181
|
+
const rawProcessing = isRecord(rawConversation.processing) ? rawConversation.processing : {};
|
|
182
|
+
const processing = {
|
|
183
|
+
activeTurnId: toOptionalString(rawProcessing.activeTurnId),
|
|
184
|
+
lastCompletedAtMs: toOptionalNumber(rawProcessing.lastCompletedAtMs),
|
|
185
|
+
pendingAuth: coercePendingAuthState(rawProcessing.pendingAuth)
|
|
186
|
+
};
|
|
187
|
+
const rawVision = isRecord(rawConversation.vision) ? rawConversation.vision : {};
|
|
188
|
+
const rawVisionByFileId = isRecord(rawVision.byFileId) ? rawVision.byFileId : {};
|
|
189
|
+
const byFileId = {};
|
|
190
|
+
for (const [fileId, value] of Object.entries(rawVisionByFileId)) {
|
|
191
|
+
if (typeof fileId !== "string" || fileId.trim().length === 0) continue;
|
|
192
|
+
if (!isRecord(value)) continue;
|
|
193
|
+
const summary = toOptionalString(value.summary);
|
|
194
|
+
const analyzedAtMs = toOptionalNumber(value.analyzedAtMs);
|
|
195
|
+
if (!summary || !analyzedAtMs) continue;
|
|
196
|
+
byFileId[fileId] = {
|
|
197
|
+
summary,
|
|
198
|
+
analyzedAtMs
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
schemaVersion: 1,
|
|
203
|
+
messages,
|
|
204
|
+
processing,
|
|
205
|
+
vision: {
|
|
206
|
+
backfillCompletedAtMs: toOptionalNumber(rawVision.backfillCompletedAtMs),
|
|
207
|
+
byFileId
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Wrap active conversation control into the thread scratch envelope.
|
|
213
|
+
*
|
|
214
|
+
* Visible history lives in SQL. Image summaries use a separate disposable
|
|
215
|
+
* cache, so thread scratch does not retain them.
|
|
216
|
+
*/
|
|
217
|
+
function buildConversationStatePatch(conversation) {
|
|
218
|
+
return { conversation: {
|
|
219
|
+
schemaVersion: 1,
|
|
220
|
+
processing: { ...conversation.processing }
|
|
221
|
+
} };
|
|
222
|
+
}
|
|
223
|
+
// src/chat/runtime/thread-state.ts
|
|
224
|
+
function threadStateKey(threadId) {
|
|
225
|
+
return `thread-state:${threadId}`;
|
|
226
|
+
}
|
|
227
|
+
function channelStateKey(channelId) {
|
|
228
|
+
return `channel-state:${channelId}`;
|
|
229
|
+
}
|
|
230
|
+
function buildThreadStatePayload(patch) {
|
|
231
|
+
const payload = {};
|
|
232
|
+
if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
|
|
233
|
+
if (patch.sandboxRef !== void 0) {
|
|
234
|
+
payload.app_sandbox_id = patch.sandboxRef?.id ?? "";
|
|
235
|
+
payload.app_sandbox_dependency_profile_hash = patch.sandboxRef?.profileHash ?? "";
|
|
236
|
+
payload.app_sandbox_workspace_id = patch.sandboxRef?.workspaceId ?? "";
|
|
237
|
+
}
|
|
238
|
+
return payload;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Merge a payload into thread scratch with Junior's TTL.
|
|
242
|
+
*
|
|
243
|
+
* Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
|
|
244
|
+
* shorter retention policy for the same scratch keys.
|
|
245
|
+
*/
|
|
246
|
+
async function mergePersistedState(key, payload) {
|
|
247
|
+
if (Object.keys(payload).length === 0) return;
|
|
248
|
+
const stateAdapter = getStateAdapter();
|
|
249
|
+
await stateAdapter.connect();
|
|
250
|
+
const existing = await stateAdapter.get(key) ?? {};
|
|
251
|
+
await stateAdapter.set(key, {
|
|
252
|
+
...existing,
|
|
253
|
+
...payload
|
|
254
|
+
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
255
|
+
}
|
|
256
|
+
/** Extract persisted sandbox metadata from thread state payload. */
|
|
257
|
+
function getPersistedSandboxState(state) {
|
|
258
|
+
const id = toOptionalString(state.app_sandbox_id);
|
|
259
|
+
if (!id) return;
|
|
260
|
+
const profileHash = toOptionalString(state.app_sandbox_dependency_profile_hash);
|
|
261
|
+
const workspaceId = toOptionalString(state.app_sandbox_workspace_id);
|
|
262
|
+
return {
|
|
263
|
+
id,
|
|
264
|
+
...profileHash ? { profileHash } : void 0,
|
|
265
|
+
...workspaceId ? { workspaceId } : void 0
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/** Persist only the Redis-backed runtime scratch in a thread-state patch. */
|
|
269
|
+
async function persistThreadRuntimeState(conversationId, patch) {
|
|
270
|
+
await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
|
|
271
|
+
}
|
|
272
|
+
/** Load the persisted state payload for a thread without requiring a Chat singleton. */
|
|
273
|
+
async function getPersistedThreadState(threadId) {
|
|
274
|
+
const stateAdapter = getStateAdapter();
|
|
275
|
+
await stateAdapter.connect();
|
|
276
|
+
return await stateAdapter.get(threadStateKey(threadId)) ?? {};
|
|
277
|
+
}
|
|
278
|
+
/** Persist a thread-state patch by thread id without constructing a Chat thread. */
|
|
279
|
+
async function persistThreadStateById(threadId, patch) {
|
|
280
|
+
if (patch.conversation) await persistConversationMessages({
|
|
281
|
+
conversation: patch.conversation,
|
|
282
|
+
conversationId: threadId
|
|
283
|
+
});
|
|
284
|
+
await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
|
|
285
|
+
}
|
|
286
|
+
/** Load legacy Redis-backed channel state during the SQL cutover. */
|
|
287
|
+
async function getLegacyChannelState(channelId) {
|
|
288
|
+
const stateAdapter = getStateAdapter();
|
|
289
|
+
await stateAdapter.connect();
|
|
290
|
+
return await stateAdapter.get(channelStateKey(channelId)) ?? {};
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Resolve durable location configuration.
|
|
294
|
+
*
|
|
295
|
+
* Slack still reads the old channel-id Redis bag once during cutover.
|
|
296
|
+
*/
|
|
297
|
+
function getLocationConfigurationService(destination) {
|
|
298
|
+
if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
|
|
299
|
+
return createDurableLocationConfigurationService({
|
|
300
|
+
destination,
|
|
301
|
+
db: getDb(),
|
|
302
|
+
loadLegacy: async () => await getLegacyChannelState(destination.channelId)
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
// src/chat/services/turn-session-routing.ts
|
|
306
|
+
async function loadConversationChain(conversationId, conversationStore) {
|
|
307
|
+
const chain = [];
|
|
308
|
+
const seen = /* @__PURE__ */ new Set();
|
|
309
|
+
let cursor = conversationId;
|
|
310
|
+
while (cursor && !seen.has(cursor)) {
|
|
311
|
+
seen.add(cursor);
|
|
312
|
+
const conversation = await conversationStore.get({ conversationId: cursor });
|
|
313
|
+
if (!conversation) break;
|
|
314
|
+
chain.push(conversation);
|
|
315
|
+
cursor = conversation.parentConversationId;
|
|
316
|
+
}
|
|
317
|
+
return chain;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Normalize a stored Slack session source against the conversation destination.
|
|
321
|
+
*
|
|
322
|
+
* Does not create channel or thread values from the conversation id.
|
|
323
|
+
*/
|
|
324
|
+
function slackSourceForDestination(args) {
|
|
325
|
+
if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
|
|
326
|
+
const threadTs = args.source.threadTs?.trim();
|
|
327
|
+
return {
|
|
328
|
+
kind: "slack",
|
|
329
|
+
visibility: args.source.visibility ?? "public",
|
|
330
|
+
teamId: args.source.teamId?.trim() || args.destination.teamId,
|
|
331
|
+
channelId: args.source.channelId,
|
|
332
|
+
...threadTs ? { threadTs } : void 0
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Resolve the Conversation Location, Destination, and session Source.
|
|
337
|
+
*
|
|
338
|
+
* Reads parent Conversations when this Conversation has no Destination.
|
|
339
|
+
*/
|
|
340
|
+
async function resolveConversationRouting(args) {
|
|
341
|
+
const conversationStore = args.conversationStore ?? (await import("./db-CoMNr2Zm.js").then((n) => n.n)).getConversationStore();
|
|
342
|
+
const chain = await loadConversationChain(args.conversationId, conversationStore);
|
|
343
|
+
let destination;
|
|
344
|
+
let source;
|
|
345
|
+
let location;
|
|
346
|
+
for (const conversation of chain) {
|
|
347
|
+
destination ??= conversation.destination;
|
|
348
|
+
source ??= conversation.sessionSource;
|
|
349
|
+
location ??= conversation.location;
|
|
350
|
+
if (destination && source) break;
|
|
351
|
+
}
|
|
352
|
+
if (!destination) return;
|
|
353
|
+
if (destination.platform === "slack") {
|
|
354
|
+
const slackSource = slackSourceForDestination({
|
|
355
|
+
destination,
|
|
356
|
+
source
|
|
357
|
+
});
|
|
358
|
+
return {
|
|
359
|
+
destination,
|
|
360
|
+
...location ? { location } : void 0,
|
|
361
|
+
...slackSource ? { source: slackSource } : void 0
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
destination,
|
|
366
|
+
...location ? { location } : void 0,
|
|
367
|
+
...source ? { source } : void 0
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
/** Require the Conversation Destination and Source from SQL. */
|
|
371
|
+
async function resolveTurnSessionRouting(args) {
|
|
372
|
+
const routing = await resolveConversationRouting(args);
|
|
373
|
+
if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
|
|
374
|
+
return {
|
|
375
|
+
destination: routing.destination,
|
|
376
|
+
...routing.location ? { location: routing.location } : void 0,
|
|
377
|
+
source: routing.source
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
export { requireValidEventTrigger as S, registeredEventMatchSchema as _, getPersistedThreadState as a, registeredResourceTypeSchema as b, coerceThreadConversationState as c, describeRegisteredEventTrigger as d, eventCatalogEntry as f, hasEventCatalogEntries as g, eventWatchUnavailable as h, getPersistedSandboxState as i, CORE_EVENT_NAMESPACE as l, eventNamespaceSchema as m, resolveTurnSessionRouting as n, persistThreadRuntimeState as o, eventGuidance as p, getLocationConfigurationService as r, persistThreadStateById as s, resolveConversationRouting as t, automationEventCatalog as u, registeredEventTriggerProblems as v, requireEventIdentifier as x, registeredEventTypeSchema as y };
|