@sentry/junior 0.318.0 → 0.319.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/{context-BKF_5zzI.js → adapter-8_S6Birm.js} +537 -537
- package/dist/{admin-UOHix_5P.js → admin-EsbUON1j.js} +1 -1
- package/dist/{agent-runner-DeYymwh2.js → agent-CtzMl32d.js} +18608 -5452
- package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
- package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-pAvsbuGL.js} +4 -5
- package/dist/api/schema.d.ts +43 -23
- package/dist/api/schema.js +4 -4
- package/dist/api.js +70 -80
- package/dist/{app-DKAOuaoC.d.ts → app-tACXxJPI.d.ts} +4 -4
- package/dist/app.d.ts +2 -2
- package/dist/app.js +213 -91
- package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
- package/dist/{channel-access-A0de5lRv.js → channel-access-DET5hzZM.js} +1 -1
- package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-DpM3tMVi.js} +5 -5
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +23 -23
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.d.ts +1 -1
- package/dist/cli/plugins.js +8 -8
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -4
- package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-CFzDyxkH.js} +3 -3
- package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
- package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-C2vYK55O.js} +1 -1
- package/dist/{create-Btl1y1rq.js → create-Ta3SEIB5.js} +115 -5
- package/dist/{credential-sync-DTarZ63K.js → credential-sync-DyRqDmY4.js} +15 -18
- package/dist/{db-of6e3sGt.js → db-BCaNWl9p.js} +4579 -717
- package/dist/{deployment-C0qXa0FD.js → deployment-CfOew1Tm.js} +3 -3
- package/dist/{engine-context-C_QL_bMQ.js → engine-context-CiExoy1B.js} +144 -149
- package/dist/{html-9_pS9SjY.js → html-Bb2Si1bR.js} +6 -8
- package/dist/instrumentation.js +7 -23
- package/dist/list-wwDcROh9.js +5007 -0
- package/dist/{logging-BnOG0qz2.js → logging-BRPTXAdf.js} +8 -33
- package/dist/{mailbox-turn-Byrry9o1.js → markers-9QoqW5ov.js} +1675 -1255
- package/dist/nitro.d.ts +2 -2
- package/dist/nitro.js +6 -7
- package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
- package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-CH2v7WiB.js} +1 -1
- package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
- package/dist/{profile-iHw1uu32.js → profile-D9LdwmZi.js} +16 -18
- package/dist/{prompt-DEkStuxG.js → prompt-3TqxEOtc.js} +1 -1
- package/dist/{reports-C1d9azyV.js → reports-K-tbtEyx.js} +2 -2
- package/dist/{resolve-DC6zBuDV.js → resolve-BBV2qf8A.js} +5 -5
- package/dist/{result-DxewDuXb.js → result-5IdGJP4M.js} +20 -9
- package/dist/{runner-99YxVN_r.js → runner-BK_joPlM.js} +7 -8
- package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
- package/dist/{schema-BTojNBr5.js → schema-zWGG6VC1.js} +13 -7
- package/dist/{service-account-YDCPSByj.js → service-account-CateFyhw.js} +4 -5
- package/dist/{skills-CleC0Hze.js → skills-Ccjw8h2P.js} +9 -9
- package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
- package/dist/storage-C9U7R5rM.js +273 -0
- package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-YBTHIFlP.js} +26 -84
- package/dist/topic-B2EWKKBT.js +6 -0
- package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
- package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
- package/dist/{users-Cb9c1k9q.js → users-CCRAqYb_.js} +1 -1
- package/dist/{validation-BiUmWPhy.js → validation-BCUpJa8K.js} +4 -4
- package/dist/{version-VEXiEcZu.js → version-BNm0JYj3.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-ChWYQdhm.js → worker-BhgpZ7_b.js} +4 -4
- package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
- package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
- package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
- package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
- package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
- package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
- package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
- package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
- package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
- package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
- package/package.json +9 -7
- package/dist/auth-pause-state-f9hJM_zO.js +0 -113
- package/dist/catalog-runtime-BfdAnztW.js +0 -6
- package/dist/child-message-peFWLcCZ.js +0 -15
- package/dist/conversation-turn-Bru4w_FD.js +0 -1250
- package/dist/job-runner-B2XEvpif.js +0 -1505
- package/dist/lineage-nh4z9iQN.js +0 -36
- package/dist/list-HRP3TIRl.js +0 -12631
- package/dist/markers-CTTtJqYn.js +0 -342
- package/dist/message-BRUuLgrY.js +0 -153
- package/dist/model-input-CFC62mf-.js +0 -82
- package/dist/registry-Cl7Labpe.js +0 -3279
- package/dist/run-conversation-Cz2ubZK-.js +0 -337
- package/dist/sender-actors-77zTQbSG.js +0 -84
- package/dist/spawn-DuZfodPa.js +0 -45
- package/dist/task-runner-BJ9Up3bG.js +0 -1529
- package/dist/topic-CRYYBYp-.js +0 -7
- package/dist/topics-BoCkoPJJ.js +0 -21
- package/dist/turn-membership-VT7XZh-L.js +0 -856
- package/dist/turn-wake-C7HeLHAM.js +0 -151
|
@@ -1,1505 +0,0 @@
|
|
|
1
|
-
import { a as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC } from "./topics-BoCkoPJJ.js";
|
|
2
|
-
import { T as withLock, n as credentialContextForActor, w as fenceLock, y as getStateAdapter } from "./context-BKF_5zzI.js";
|
|
3
|
-
import { $n as resolveEventMentions, Br as QUEUE_SIGNATURE_MAX_AGE_MS, Hr as verifyQueueMessage, Ji as createSandboxCapability, Nr as getVercelConversationWorkQueue, Oo as deliverWatch, Pi as slackMention, Ui as createPluginModel, Ur as getQueueProvider, Vi as createPluginDecider, Vr as signQueueMessage, Vs as sleep, Wi as createPluginModelCostRecorder, Xi as withPluginHookSpan, a as getDb, au as ToolInputError, gf as juniorSpaceConfigurations, go as workspaceSnapshotFinishedEvent, hf as juniorConversations, jo as isQuietEvent, jt as juniorToolOutputSchema, ko as findMatchingWatches, ou as isToolInputError, qi as basePluginContext, qs as readActorIdentity, rs as createPluginAnnotations, ur as getTurnRequestDeadline, wt as getRegistrations } from "./db-of6e3sGt.js";
|
|
4
|
-
import { Fn as isValidTimeZone, Pn as getZonedDateTimeParts } from "./types-DCzTAA63.js";
|
|
5
|
-
import { f as logException, m as logWarn, p as logInfo } from "./logging-BnOG0qz2.js";
|
|
6
|
-
import { c as SANDBOX_REPOS_ROOT, d as SANDBOX_WORKSPACE_ROOT, s as SANDBOX_JUNIOR_ROOT } from "./prompt-DEkStuxG.js";
|
|
7
|
-
import { $t as invalidateReadySnapshot, B as resolveEventAuthor, Qt as workspaceRepoCheckoutPath, Wt as getWorkspace, ci as configValueSchema, en as loadSnapshotsForProfile, j as enqueueEventNotification, k as addQuietEventNote, nn as setWorkspaceSnapshotBuild, oi as validateConfigKey, si as validateConfigValue, tn as setWorkspaceSnapshot } from "./mailbox-turn-Byrry9o1.js";
|
|
8
|
-
import { E as createSandboxEgressCredentialToken, _ as WorkspaceSnapshotNotReadyError, j as buildSandboxEgressNetworkPolicy, o as getSandboxProvider, p as isAbortError, r as isStale, t as create, u as SANDBOX_RUNTIME, y as isWorkspaceSnapshotNotReadyError } from "./profile-iHw1uu32.js";
|
|
9
|
-
import { i as postinstall, o as getSandboxResources, r as dependencies } from "./resolve-DC6zBuDV.js";
|
|
10
|
-
import * as z from "zod";
|
|
11
|
-
import path from "node:path";
|
|
12
|
-
import { and, asc, eq, sql } from "drizzle-orm";
|
|
13
|
-
import { alias } from "drizzle-orm/pg-core";
|
|
14
|
-
import { escapeTagTextAndQuotes, eventSchema, objectAnnotationSchema, renderInlineTag } from "@sentry/junior-plugin-api";
|
|
15
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
16
|
-
import { structuredPatch } from "diff";
|
|
17
|
-
// src/chat/spaces/configuration.ts
|
|
18
|
-
/**
|
|
19
|
-
* Configuration of a Space: the same keys that a Slack channel sets, such as
|
|
20
|
-
* a default repository. A value applies to every Conversation in the Space.
|
|
21
|
-
* It wins over the Slack channel's value and the install default, and an
|
|
22
|
-
* explicit target in a request wins over it.
|
|
23
|
-
*/
|
|
24
|
-
const rootConversation = alias(juniorConversations, "space_config_root");
|
|
25
|
-
/** List the configuration of a Space, by key. */
|
|
26
|
-
async function listSpaceConfiguration(spaceId) {
|
|
27
|
-
return (await getDb().select({
|
|
28
|
-
key: juniorSpaceConfigurations.key,
|
|
29
|
-
value: juniorSpaceConfigurations.value,
|
|
30
|
-
updatedAt: juniorSpaceConfigurations.updatedAt
|
|
31
|
-
}).from(juniorSpaceConfigurations).where(eq(juniorSpaceConfigurations.spaceId, spaceId)).orderBy(asc(juniorSpaceConfigurations.key))).map((row) => ({
|
|
32
|
-
...row,
|
|
33
|
-
value: configValueSchema.parse(JSON.parse(row.value))
|
|
34
|
-
}));
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Set one configuration value of a Space. Returns an error message when the
|
|
38
|
-
* key or the value is not allowed, such as a secret.
|
|
39
|
-
*/
|
|
40
|
-
async function setSpaceConfiguration(args) {
|
|
41
|
-
const error = validateConfigKey(args.key) ?? validateConfigValue(args.value);
|
|
42
|
-
if (error) return error;
|
|
43
|
-
const values = {
|
|
44
|
-
value: JSON.stringify(args.value),
|
|
45
|
-
updatedAt: /* @__PURE__ */ new Date(),
|
|
46
|
-
updatedByUserId: args.updatedByUserId
|
|
47
|
-
};
|
|
48
|
-
await getDb().insert(juniorSpaceConfigurations).values({
|
|
49
|
-
spaceId: args.spaceId,
|
|
50
|
-
key: args.key,
|
|
51
|
-
...values
|
|
52
|
-
}).onConflictDoUpdate({
|
|
53
|
-
target: [juniorSpaceConfigurations.spaceId, juniorSpaceConfigurations.key],
|
|
54
|
-
set: values
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
/** Remove one configuration value of a Space. */
|
|
58
|
-
async function unsetSpaceConfiguration(spaceId, key) {
|
|
59
|
-
await getDb().delete(juniorSpaceConfigurations).where(and(eq(juniorSpaceConfigurations.spaceId, spaceId), eq(juniorSpaceConfigurations.key, key)));
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Return the id of the Space that a Conversation's root is in, if any. In a
|
|
63
|
-
* Space, the root is the Space's Lead.
|
|
64
|
-
*/
|
|
65
|
-
async function readConversationSpaceId(conversationId) {
|
|
66
|
-
const [row] = await getDb().select({ spaceId: rootConversation.spaceId }).from(juniorConversations).innerJoin(rootConversation, eq(rootConversation.conversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
67
|
-
return row?.spaceId ?? void 0;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Return the configuration of the Space that a Conversation's root is in. A
|
|
71
|
-
* child is in the Space of its root. A Conversation outside a Space has none.
|
|
72
|
-
*/
|
|
73
|
-
async function readConversationSpaceConfiguration(conversationId) {
|
|
74
|
-
const rows = await getDb().select({
|
|
75
|
-
key: juniorSpaceConfigurations.key,
|
|
76
|
-
value: juniorSpaceConfigurations.value
|
|
77
|
-
}).from(juniorConversations).innerJoin(rootConversation, eq(rootConversation.conversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).innerJoin(juniorSpaceConfigurations, eq(juniorSpaceConfigurations.spaceId, rootConversation.spaceId)).where(eq(juniorConversations.conversationId, conversationId));
|
|
78
|
-
return Object.fromEntries(rows.map((row) => [row.key, configValueSchema.parse(JSON.parse(row.value))]));
|
|
79
|
-
}
|
|
80
|
-
// src/chat/tool-support/zod-tool.ts
|
|
81
|
-
function isContentOnlyToolResult(value) {
|
|
82
|
-
return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
|
|
83
|
-
}
|
|
84
|
-
function isStructuredToolResultEnvelope(value) {
|
|
85
|
-
return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
|
|
86
|
-
}
|
|
87
|
-
function parseToolContent(content) {
|
|
88
|
-
for (const item of content) if (!item || typeof item !== "object" || (item.type === "text" ? typeof item.text !== "string" : item.type === "image" ? typeof item.data !== "string" || typeof item.mimeType !== "string" : true)) throw new TypeError("zodTool() content must contain valid text or image items.");
|
|
89
|
-
return content;
|
|
90
|
-
}
|
|
91
|
-
function formatZodPath(path) {
|
|
92
|
-
return path.length > 0 ? path.map(String).join(".") : "root";
|
|
93
|
-
}
|
|
94
|
-
function formatToolInputError(error) {
|
|
95
|
-
return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
|
|
96
|
-
}
|
|
97
|
-
/** Parse tool input with its Zod schema, as a model-repairable error on failure. */
|
|
98
|
-
function parseToolInput(schema, args) {
|
|
99
|
-
const result = schema.safeParse(args);
|
|
100
|
-
if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
|
|
101
|
-
return result.data;
|
|
102
|
-
}
|
|
103
|
-
/** Declare the static definition of a Zod tool once, for the registry and its factory. */
|
|
104
|
-
function zodToolDefinition(definition) {
|
|
105
|
-
return definition;
|
|
106
|
-
}
|
|
107
|
-
function zodTool(definition) {
|
|
108
|
-
const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
|
|
109
|
-
let modelInputSchema;
|
|
110
|
-
try {
|
|
111
|
-
modelInputSchema = z.toJSONSchema(inputSchema);
|
|
112
|
-
} catch (error) {
|
|
113
|
-
throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
|
|
114
|
-
}
|
|
115
|
-
let modelOutputSchema;
|
|
116
|
-
if (outputSchema) try {
|
|
117
|
-
modelOutputSchema = z.toJSONSchema(outputSchema);
|
|
118
|
-
} catch (error) {
|
|
119
|
-
throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
|
|
120
|
-
}
|
|
121
|
-
return {
|
|
122
|
-
...toolDef,
|
|
123
|
-
inputSchema: modelInputSchema,
|
|
124
|
-
...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
|
|
125
|
-
prepareArguments(args) {
|
|
126
|
-
return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
|
|
127
|
-
},
|
|
128
|
-
...execute ? { async execute(input, options) {
|
|
129
|
-
const result = await execute(input, options);
|
|
130
|
-
if (!outputSchema) {
|
|
131
|
-
if (isContentOnlyToolResult(result)) return result;
|
|
132
|
-
throw new TypeError("zodTool() content-only tools must return { content } without details.");
|
|
133
|
-
}
|
|
134
|
-
if (isStructuredToolResultEnvelope(result)) return {
|
|
135
|
-
content: parseToolContent(result.content),
|
|
136
|
-
details: outputSchema.parse(result.details)
|
|
137
|
-
};
|
|
138
|
-
return outputSchema.parse(result);
|
|
139
|
-
} } : void 0
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
// src/chat/conversations/annotation-results.ts
|
|
143
|
-
/** Save object annotations and retain returned facts in the tool result. */
|
|
144
|
-
async function saveObjectAnnotations(conversationId, plugin, value) {
|
|
145
|
-
const annotations = objectAnnotationSchema.array().parse(value);
|
|
146
|
-
await getDb().transaction(async (db) => {
|
|
147
|
-
const store = createPluginAnnotations({
|
|
148
|
-
conversationId,
|
|
149
|
-
plugin,
|
|
150
|
-
db
|
|
151
|
-
});
|
|
152
|
-
for (const annotation of annotations) {
|
|
153
|
-
await store.upsert(annotation);
|
|
154
|
-
await store.remove("resource_link", annotation.key);
|
|
155
|
-
}
|
|
156
|
-
});
|
|
157
|
-
return annotations.map((annotation) => ({
|
|
158
|
-
...annotation,
|
|
159
|
-
plugin
|
|
160
|
-
}));
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Save annotations from a successful plugin tool result and attach their cards.
|
|
164
|
-
* An Annotation marks work that the Conversation did, so a read-only tool must
|
|
165
|
-
* not return one: looking up an object does not link it.
|
|
166
|
-
*/
|
|
167
|
-
async function annotateToolResult(conversationId, plugin, result, options) {
|
|
168
|
-
if (typeof result !== "object" || result === null) return result;
|
|
169
|
-
if ("isError" in result && result.isError === true) return result;
|
|
170
|
-
const details = "details" in result && typeof result.details === "object" && result.details !== null ? result.details : result;
|
|
171
|
-
if ("timed_out" in details && details.timed_out === true || "isError" in details && details.isError === true || !("objectAnnotations" in details) || !Array.isArray(details.objectAnnotations)) return result;
|
|
172
|
-
if (options.readOnly) throw new Error(`Read-only ${plugin} tool returned objectAnnotations. Return them only from tools that change the object.`);
|
|
173
|
-
const cards = await saveObjectAnnotations(conversationId, plugin, details.objectAnnotations);
|
|
174
|
-
const { objectAnnotations: _annotations, ...rest } = details;
|
|
175
|
-
const annotated = {
|
|
176
|
-
...rest,
|
|
177
|
-
objectCards: cards
|
|
178
|
-
};
|
|
179
|
-
if (details !== result) return {
|
|
180
|
-
...result,
|
|
181
|
-
details: annotated
|
|
182
|
-
};
|
|
183
|
-
return annotated;
|
|
184
|
-
}
|
|
185
|
-
// src/chat/sandbox/file-utils.ts
|
|
186
|
-
/** Normalize model-supplied numeric knobs before they reach filesystem tools. */
|
|
187
|
-
function positiveInteger(value) {
|
|
188
|
-
if (typeof value !== "number" || !Number.isFinite(value)) return;
|
|
189
|
-
const integer = Math.floor(value);
|
|
190
|
-
return integer > 0 ? integer : void 0;
|
|
191
|
-
}
|
|
192
|
-
/** Compare and slice text in one line-ending space while preserving callers' output rules. */
|
|
193
|
-
function normalizeToLf(value) {
|
|
194
|
-
return value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
195
|
-
}
|
|
196
|
-
/** Detect model-facing missing paths without swallowing sandbox lifecycle/API failures. */
|
|
197
|
-
function isMissingPathError(error) {
|
|
198
|
-
if (!error || typeof error !== "object") return false;
|
|
199
|
-
const candidate = error;
|
|
200
|
-
if (candidate.code === "ENOENT") return true;
|
|
201
|
-
return typeof candidate.message === "string" && candidate.message.startsWith("File not found:");
|
|
202
|
-
}
|
|
203
|
-
const SANDBOX_FILE_ROOTS = [SANDBOX_WORKSPACE_ROOT, "/tmp"];
|
|
204
|
-
/** Keep sandbox filesystem tools scoped to the workspace root and /tmp. */
|
|
205
|
-
function resolveWorkspacePath(input, fallback = ".") {
|
|
206
|
-
const requested = (input ?? "").trim() || fallback;
|
|
207
|
-
const absolute = requested.startsWith("/") ? requested : path.posix.join(SANDBOX_WORKSPACE_ROOT, requested);
|
|
208
|
-
const normalized = path.posix.normalize(absolute);
|
|
209
|
-
if (!SANDBOX_FILE_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`))) throw new ToolInputError(`Path must stay within ${SANDBOX_FILE_ROOTS.join(" or ")}: ${requested}`);
|
|
210
|
-
return normalized;
|
|
211
|
-
}
|
|
212
|
-
// src/chat/tool-support/text-edits.ts
|
|
213
|
-
const MAX_DIFF_LINE_CHARS = 4e3;
|
|
214
|
-
/** Preserve a text artifact's dominant line-ending style across rewrites. */
|
|
215
|
-
function detectLineEnding(value) {
|
|
216
|
-
return value.includes("\r\n") ? "\r\n" : "\n";
|
|
217
|
-
}
|
|
218
|
-
/** Restore normalized LF content to the caller's original line-ending style. */
|
|
219
|
-
function restoreLineEndings(value, lineEnding) {
|
|
220
|
-
return lineEnding === "\r\n" ? value.replace(/\n/g, "\r\n") : value;
|
|
221
|
-
}
|
|
222
|
-
/** Keep UTF-8 BOM handling out of exact edit matching. */
|
|
223
|
-
function stripBom(value) {
|
|
224
|
-
return value.startsWith("") ? {
|
|
225
|
-
bom: "",
|
|
226
|
-
text: value.slice(1)
|
|
227
|
-
} : {
|
|
228
|
-
bom: "",
|
|
229
|
-
text: value
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
function countOccurrences(content, target) {
|
|
233
|
-
let count = 0;
|
|
234
|
-
let start = 0;
|
|
235
|
-
while (target.length > 0) {
|
|
236
|
-
const index = content.indexOf(target, start);
|
|
237
|
-
if (index === -1) break;
|
|
238
|
-
count += 1;
|
|
239
|
-
start = index + target.length;
|
|
240
|
-
}
|
|
241
|
-
return count;
|
|
242
|
-
}
|
|
243
|
-
function firstChangedLine(oldLines, newLines) {
|
|
244
|
-
const count = Math.max(oldLines.length, newLines.length);
|
|
245
|
-
for (let index = 0; index < count; index += 1) if (oldLines[index] !== newLines[index]) return index + 1;
|
|
246
|
-
}
|
|
247
|
-
/**
|
|
248
|
-
* Accept common exact-edit argument variants, such as the camelCase keys that
|
|
249
|
-
* models often send, before schema validation.
|
|
250
|
-
*/
|
|
251
|
-
function prepareTextReplacementArguments(input) {
|
|
252
|
-
if (!input || typeof input !== "object") return input;
|
|
253
|
-
const raw = { ...input };
|
|
254
|
-
if (typeof raw["edits"] === "string") try {
|
|
255
|
-
raw["edits"] = JSON.parse(raw["edits"]);
|
|
256
|
-
} catch {
|
|
257
|
-
return raw;
|
|
258
|
-
}
|
|
259
|
-
const edits = Array.isArray(raw["edits"]) ? Array.from(raw["edits"]) : [];
|
|
260
|
-
const oldText = raw["old_text"] ?? raw["oldText"];
|
|
261
|
-
const newText = raw["new_text"] ?? raw["newText"];
|
|
262
|
-
if (typeof oldText === "string" && typeof newText === "string") edits.push({
|
|
263
|
-
old_text: oldText,
|
|
264
|
-
new_text: newText
|
|
265
|
-
});
|
|
266
|
-
if (edits.length > 0) raw["edits"] = edits.map((edit) => {
|
|
267
|
-
if (!edit || typeof edit !== "object") return edit;
|
|
268
|
-
const record = edit;
|
|
269
|
-
const { oldText, newText, ...rest } = record;
|
|
270
|
-
return {
|
|
271
|
-
...rest,
|
|
272
|
-
old_text: record["old_text"] ?? oldText,
|
|
273
|
-
new_text: record["new_text"] ?? newText
|
|
274
|
-
};
|
|
275
|
-
});
|
|
276
|
-
delete raw["oldText"];
|
|
277
|
-
delete raw["old_text"];
|
|
278
|
-
delete raw["newText"];
|
|
279
|
-
delete raw["new_text"];
|
|
280
|
-
return raw;
|
|
281
|
-
}
|
|
282
|
-
/** Build a small line-oriented diff that gives agents enough context to review edits. */
|
|
283
|
-
function buildCompactDiff(oldContent, newContent) {
|
|
284
|
-
const oldLines = oldContent.split("\n");
|
|
285
|
-
const newLines = newContent.split("\n");
|
|
286
|
-
const { hunks } = structuredPatch("", "", oldContent, newContent, void 0, void 0, { context: 3 });
|
|
287
|
-
const width = String(Math.max(oldLines.length, newLines.length)).length;
|
|
288
|
-
const output = [];
|
|
289
|
-
let lineTruncated = false;
|
|
290
|
-
const pushLine = (line) => {
|
|
291
|
-
if (line.length > MAX_DIFF_LINE_CHARS) {
|
|
292
|
-
line = `${line.slice(0, MAX_DIFF_LINE_CHARS)}... [line truncated]`;
|
|
293
|
-
lineTruncated = true;
|
|
294
|
-
}
|
|
295
|
-
output.push(line);
|
|
296
|
-
};
|
|
297
|
-
let nextLine = 1;
|
|
298
|
-
for (const hunk of hunks) {
|
|
299
|
-
if (hunk.newStart > nextLine) pushLine(` ${"".padStart(width)} ...`);
|
|
300
|
-
let oldLine = hunk.oldStart;
|
|
301
|
-
let newLine = hunk.newStart;
|
|
302
|
-
for (const line of hunk.lines) {
|
|
303
|
-
const prefix = line[0];
|
|
304
|
-
if (prefix === "\\") {
|
|
305
|
-
pushLine(line);
|
|
306
|
-
continue;
|
|
307
|
-
}
|
|
308
|
-
pushLine(`${prefix}${String(prefix === "-" ? oldLine : newLine).padStart(width)} ${line.slice(1)}`);
|
|
309
|
-
if (prefix !== "+") oldLine += 1;
|
|
310
|
-
if (prefix !== "-") newLine += 1;
|
|
311
|
-
}
|
|
312
|
-
nextLine = newLine;
|
|
313
|
-
}
|
|
314
|
-
const newLineCount = newContent ? newLines.length - (newContent.endsWith("\n") ? 1 : 0) : 0;
|
|
315
|
-
if (hunks.length > 0 && nextLine <= newLineCount) pushLine(` ${"".padStart(width)} ...`);
|
|
316
|
-
return {
|
|
317
|
-
diff: output.join("\n"),
|
|
318
|
-
firstChangedLine: firstChangedLine(oldLines, newLines),
|
|
319
|
-
truncated: lineTruncated
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
/** Apply exact replacements to normalized text after validating uniqueness and overlap. */
|
|
323
|
-
function validateAndApplyTextEdits(content, edits, targetName) {
|
|
324
|
-
if (!Array.isArray(edits) || edits.length === 0) throw new ToolInputError(`${targetName} requires at least one edit.`);
|
|
325
|
-
const normalizedEdits = edits.map((edit, index) => {
|
|
326
|
-
if (typeof edit.old_text !== "string" || edit.old_text.length === 0) throw new ToolInputError(`edits[${index}].old_text must not be empty in ${targetName}.`);
|
|
327
|
-
if (typeof edit.new_text !== "string") throw new ToolInputError(`edits[${index}].new_text must be a string in ${targetName}.`);
|
|
328
|
-
return {
|
|
329
|
-
oldText: normalizeToLf(edit.old_text),
|
|
330
|
-
newText: normalizeToLf(edit.new_text)
|
|
331
|
-
};
|
|
332
|
-
});
|
|
333
|
-
const matchedEdits = [];
|
|
334
|
-
for (const [index, edit] of normalizedEdits.entries()) {
|
|
335
|
-
const matchIndex = content.indexOf(edit.oldText);
|
|
336
|
-
if (matchIndex === -1) throw new ToolInputError(`Could not find edits[${index}] in ${targetName}. old_text must match exactly including whitespace and newlines.`);
|
|
337
|
-
const occurrences = countOccurrences(content, edit.oldText);
|
|
338
|
-
if (occurrences > 1) throw new ToolInputError(`Found ${occurrences} occurrences of edits[${index}] in ${targetName}. Each old_text must be unique. Add surrounding text to old_text so that it matches once.`);
|
|
339
|
-
matchedEdits.push({
|
|
340
|
-
editIndex: index,
|
|
341
|
-
matchIndex,
|
|
342
|
-
matchLength: edit.oldText.length,
|
|
343
|
-
newText: edit.newText
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
matchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);
|
|
347
|
-
for (const [index, current] of matchedEdits.entries()) {
|
|
348
|
-
const previous = matchedEdits[index - 1];
|
|
349
|
-
if (!previous) continue;
|
|
350
|
-
if (previous.matchIndex + previous.matchLength > current.matchIndex) throw new ToolInputError(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${targetName}. Merge overlapping replacements into one edit.`);
|
|
351
|
-
}
|
|
352
|
-
let newContent = content;
|
|
353
|
-
for (const edit of [...matchedEdits].reverse()) newContent = newContent.slice(0, edit.matchIndex) + edit.newText + newContent.slice(edit.matchIndex + edit.matchLength);
|
|
354
|
-
if (newContent === content) throw new ToolInputError(`No changes made to ${targetName}. Set new_text to text that differs from old_text, or remove that edit.`);
|
|
355
|
-
return {
|
|
356
|
-
baseContent: content,
|
|
357
|
-
newContent
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
// src/chat/tools/sandbox/bash.ts
|
|
361
|
-
const bashToolDefinition = zodToolDefinition({
|
|
362
|
-
annotations: {
|
|
363
|
-
destructiveHint: true,
|
|
364
|
-
idempotentHint: false,
|
|
365
|
-
openWorldHint: false,
|
|
366
|
-
readOnlyHint: false
|
|
367
|
-
},
|
|
368
|
-
description: "Run a bash command inside the isolated sandbox workspace. Use this for repository inspection/execution tasks that need shell access. Do not use for network-sensitive or destructive actions unless explicitly required.",
|
|
369
|
-
inputSchema: z.object({
|
|
370
|
-
command: z.string().min(1).describe("Bash command to run inside the sandbox."),
|
|
371
|
-
cwd: z.string().min(1).describe("Optional working directory for this command only.").optional(),
|
|
372
|
-
timeout_ms: z.coerce.number().int().min(1e3).describe("Optional command timeout in milliseconds. Use for commands that may hang.").optional()
|
|
373
|
-
}),
|
|
374
|
-
outputSchema: juniorToolOutputSchema,
|
|
375
|
-
executionMode: "sequential"
|
|
376
|
-
});
|
|
377
|
-
/** Create the sandbox shell tool definition exposed to the agent. */
|
|
378
|
-
function createBashTool() {
|
|
379
|
-
return zodTool({
|
|
380
|
-
...bashToolDefinition,
|
|
381
|
-
execute: async () => {
|
|
382
|
-
throw new Error("bash can only run when sandbox execution is enabled.");
|
|
383
|
-
}
|
|
384
|
-
});
|
|
385
|
-
}
|
|
386
|
-
// src/chat/tools/sandbox/edit-file.ts
|
|
387
|
-
/** Accept common edit argument variants before Pi validates the canonical schema. */
|
|
388
|
-
function prepareEditFileArguments(input) {
|
|
389
|
-
return prepareTextReplacementArguments(input);
|
|
390
|
-
}
|
|
391
|
-
const editReplacementSchema = z.object({
|
|
392
|
-
old_text: z.string().min(1).describe("Exact text to replace. It must be unique in the original file and must not overlap another edit."),
|
|
393
|
-
new_text: z.string().describe("Replacement text for this edit.")
|
|
394
|
-
});
|
|
395
|
-
const editFileToolDefinition = zodToolDefinition({
|
|
396
|
-
annotations: {
|
|
397
|
-
destructiveHint: true,
|
|
398
|
-
idempotentHint: true,
|
|
399
|
-
openWorldHint: false,
|
|
400
|
-
readOnlyHint: false
|
|
401
|
-
},
|
|
402
|
-
description: "Edit one sandbox workspace file with exact text replacements. Use for precise changes to existing files; prefer this over writeFile for targeted changes. Returns a diff. Multiple changes to the same file: use one edits[] call.",
|
|
403
|
-
prepareArguments: prepareEditFileArguments,
|
|
404
|
-
executionMode: "sequential",
|
|
405
|
-
inputSchema: z.object({
|
|
406
|
-
path: z.string().min(1).describe("Path to edit in the sandbox workspace."),
|
|
407
|
-
edits: z.array(editReplacementSchema).min(1).describe("Exact replacements matched against the original file, not incrementally.")
|
|
408
|
-
}),
|
|
409
|
-
outputSchema: juniorToolOutputSchema
|
|
410
|
-
});
|
|
411
|
-
/** Create the sandbox edit tool definition exposed to the agent. */
|
|
412
|
-
function createEditFileTool() {
|
|
413
|
-
return zodTool({
|
|
414
|
-
...editFileToolDefinition,
|
|
415
|
-
execute: async () => {
|
|
416
|
-
throw new Error("editFile can only run when sandbox execution is enabled.");
|
|
417
|
-
}
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
// src/chat/tools/sandbox/read-file.ts
|
|
421
|
-
const readFileToolDefinition = zodToolDefinition({
|
|
422
|
-
description: "Read a bounded line range from a file in the sandbox workspace. Use when you need exact file contents to verify facts or make edits safely. Use bash (rg, find, ls) for broad discovery.",
|
|
423
|
-
annotations: {
|
|
424
|
-
destructiveHint: false,
|
|
425
|
-
idempotentHint: true,
|
|
426
|
-
openWorldHint: false,
|
|
427
|
-
readOnlyHint: true
|
|
428
|
-
},
|
|
429
|
-
inputSchema: z.object({
|
|
430
|
-
path: z.string().min(1).describe("Path to the file in the sandbox workspace."),
|
|
431
|
-
offset: z.coerce.number().int().min(1).describe("1-indexed line number to start reading from.").optional(),
|
|
432
|
-
limit: z.coerce.number().int().min(1).describe("Maximum number of lines to read. Defaults to 1000.").optional()
|
|
433
|
-
}),
|
|
434
|
-
outputSchema: juniorToolOutputSchema
|
|
435
|
-
});
|
|
436
|
-
/** Create the sandbox read tool definition exposed to the agent. */
|
|
437
|
-
function createReadFileTool() {
|
|
438
|
-
return zodTool({
|
|
439
|
-
...readFileToolDefinition,
|
|
440
|
-
execute: async () => {
|
|
441
|
-
throw new Error("readFile can only run when sandbox execution is enabled.");
|
|
442
|
-
}
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
// src/chat/tools/sandbox/write-file.ts
|
|
446
|
-
const writeFileToolDefinition = zodToolDefinition({
|
|
447
|
-
annotations: {
|
|
448
|
-
destructiveHint: true,
|
|
449
|
-
idempotentHint: true,
|
|
450
|
-
openWorldHint: false,
|
|
451
|
-
readOnlyHint: false
|
|
452
|
-
},
|
|
453
|
-
description: "Write UTF-8 content to a file in the sandbox workspace. Use for intentional file creation or deliberate full-file replacement after validation; use editFile instead for targeted changes to existing files. Do not use for exploratory analysis-only turns.",
|
|
454
|
-
executionMode: "sequential",
|
|
455
|
-
inputSchema: z.object({
|
|
456
|
-
path: z.string().min(1).describe("Path to write in the sandbox workspace."),
|
|
457
|
-
content: z.string().describe("UTF-8 file content to write.")
|
|
458
|
-
}),
|
|
459
|
-
outputSchema: juniorToolOutputSchema
|
|
460
|
-
});
|
|
461
|
-
/** Create the sandbox full-file write tool definition exposed to the agent. */
|
|
462
|
-
function createWriteFileTool() {
|
|
463
|
-
return zodTool({
|
|
464
|
-
...writeFileToolDefinition,
|
|
465
|
-
execute: async () => {
|
|
466
|
-
throw new Error("writeFile can only run when sandbox execution is enabled.");
|
|
467
|
-
}
|
|
468
|
-
});
|
|
469
|
-
}
|
|
470
|
-
const systemTimeToolDefinition = zodToolDefinition({
|
|
471
|
-
description: "Return current system time in UTC and optional local IANA timezone formats. Use when the user asks for current time/date context. Pass timezone when the answer should be in a known IANA zone such as America/Los_Angeles.",
|
|
472
|
-
annotations: {
|
|
473
|
-
destructiveHint: false,
|
|
474
|
-
idempotentHint: true,
|
|
475
|
-
openWorldHint: false,
|
|
476
|
-
readOnlyHint: true
|
|
477
|
-
},
|
|
478
|
-
inputSchema: z.object({ timezone: z.string().trim().min(1).optional().describe("Optional IANA timezone, for example America/Los_Angeles. When set, iso_local and timezone_offset_minutes are for that zone.") }),
|
|
479
|
-
outputSchema: juniorToolOutputSchema.extend({
|
|
480
|
-
unix_ms: z.number().describe("Current time in epoch milliseconds, for millisecond inputs."),
|
|
481
|
-
iso_utc: z.string(),
|
|
482
|
-
iso_local: z.string(),
|
|
483
|
-
timezone: z.string().nullable(),
|
|
484
|
-
timezone_offset_minutes: z.number()
|
|
485
|
-
}),
|
|
486
|
-
privateTraceResult: (result) => ({
|
|
487
|
-
unix_ms: result.unix_ms,
|
|
488
|
-
iso_utc: result.iso_utc,
|
|
489
|
-
iso_local: result.iso_local,
|
|
490
|
-
timezone: result.timezone,
|
|
491
|
-
timezone_offset_minutes: result.timezone_offset_minutes
|
|
492
|
-
})
|
|
493
|
-
});
|
|
494
|
-
/**
|
|
495
|
-
* Current-time lookup for turn answers.
|
|
496
|
-
*
|
|
497
|
-
* Accept an optional IANA timezone so remembered local-time preferences can be
|
|
498
|
-
* answered without shelling out to bash for conversion.
|
|
499
|
-
*/
|
|
500
|
-
function createSystemTimeTool() {
|
|
501
|
-
return zodTool({
|
|
502
|
-
...systemTimeToolDefinition,
|
|
503
|
-
execute: async (input) => {
|
|
504
|
-
const now = /* @__PURE__ */ new Date();
|
|
505
|
-
const timezone = input.timezone?.trim() || null;
|
|
506
|
-
if (timezone) {
|
|
507
|
-
if (!isValidTimeZone(timezone)) throw new ToolInputError("timezone must be a valid IANA time zone.");
|
|
508
|
-
const parts = getZonedDateTimeParts(now.getTime(), timezone);
|
|
509
|
-
const isoLocal = [
|
|
510
|
-
String(parts.year).padStart(4, "0"),
|
|
511
|
-
String(parts.month).padStart(2, "0"),
|
|
512
|
-
String(parts.day).padStart(2, "0")
|
|
513
|
-
].join("-") + "T" + [
|
|
514
|
-
String(parts.hour).padStart(2, "0"),
|
|
515
|
-
String(parts.minute).padStart(2, "0"),
|
|
516
|
-
String(parts.second).padStart(2, "0")
|
|
517
|
-
].join(":");
|
|
518
|
-
return {
|
|
519
|
-
unix_ms: now.getTime(),
|
|
520
|
-
iso_utc: now.toISOString(),
|
|
521
|
-
iso_local: isoLocal,
|
|
522
|
-
timezone,
|
|
523
|
-
timezone_offset_minutes: getTimeZoneOffsetMinutes(now.getTime(), timezone)
|
|
524
|
-
};
|
|
525
|
-
}
|
|
526
|
-
return {
|
|
527
|
-
unix_ms: now.getTime(),
|
|
528
|
-
iso_utc: now.toISOString(),
|
|
529
|
-
iso_local: (/* @__PURE__ */ new Date(now.getTime() - now.getTimezoneOffset() * 6e4)).toISOString().replace("Z", ""),
|
|
530
|
-
timezone: null,
|
|
531
|
-
timezone_offset_minutes: now.getTimezoneOffset()
|
|
532
|
-
};
|
|
533
|
-
}
|
|
534
|
-
});
|
|
535
|
-
}
|
|
536
|
-
function getTimeZoneOffsetMinutes(timestampMs, timezone) {
|
|
537
|
-
const parts = getZonedDateTimeParts(timestampMs, timezone);
|
|
538
|
-
const asUtcMs = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
|
539
|
-
return Math.round((timestampMs - asUtcMs) / 6e4);
|
|
540
|
-
}
|
|
541
|
-
// src/chat/tool-support/plugin-tool-denied-error.ts
|
|
542
|
-
const NOT_RUN_LINE = "This action was blocked by policy and was not executed.";
|
|
543
|
-
const RAN_LINE = "This action ran, but policy rejected its result. Its changes may still be in place.";
|
|
544
|
-
const PLUGIN_DENIAL_INSTRUCTIONS = ["Do not retry it or reach the same result through a workaround or another tool.", "Stop and explain what was blocked and why."].join("\n");
|
|
545
|
-
/** Expected tool failure when a plugin hook refuses a tool call by policy. */
|
|
546
|
-
var PluginToolDeniedError = class extends Error {
|
|
547
|
-
/** `ran` is true when an after-execution hook rejected the result. */
|
|
548
|
-
constructor(reason, options = {}) {
|
|
549
|
-
super(`${options.ran ? RAN_LINE : NOT_RUN_LINE}\n${PLUGIN_DENIAL_INSTRUCTIONS}\nReason: ${reason}`);
|
|
550
|
-
this.name = "PluginToolDeniedError";
|
|
551
|
-
}
|
|
552
|
-
};
|
|
553
|
-
// src/chat/plugins/after-tool-hooks.ts
|
|
554
|
-
/** Render a nudge as the marked text the agent reads. */
|
|
555
|
-
function renderToolResultNudge(nudge) {
|
|
556
|
-
return renderInlineTag("plugin-note", escapeTagTextAndQuotes(nudge.message), { plugin: nudge.pluginName });
|
|
557
|
-
}
|
|
558
|
-
async function activeWorkspace(sandbox) {
|
|
559
|
-
const id = sandbox.workspaceId();
|
|
560
|
-
const workspace = id ? await getWorkspace(getDb(), id) : void 0;
|
|
561
|
-
if (!workspace) return void 0;
|
|
562
|
-
return {
|
|
563
|
-
name: workspace.name,
|
|
564
|
-
repos: workspace.repos.map((repo) => ({
|
|
565
|
-
path: workspaceRepoCheckoutPath(repo.repo),
|
|
566
|
-
provider: repo.provider,
|
|
567
|
-
repo: repo.repo
|
|
568
|
-
}))
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
/**
|
|
572
|
-
* Run each plugin's `afterToolExecute` hook in registration order. A denial
|
|
573
|
-
* throws `PluginToolDeniedError` and skips later hooks. An abort stops the
|
|
574
|
-
* checks and keeps the tool result.
|
|
575
|
-
*/
|
|
576
|
-
async function runAfterToolExecuteHooks(args) {
|
|
577
|
-
const hooked = args.plugins.filter((plugin) => plugin.hooks?.afterToolExecute);
|
|
578
|
-
if (hooked.length === 0) return [];
|
|
579
|
-
const { signal } = args.tool;
|
|
580
|
-
const sandbox = createSandboxCapability(args.sandbox.workspace, signal);
|
|
581
|
-
let workspace;
|
|
582
|
-
try {
|
|
583
|
-
workspace = await activeWorkspace(args.sandbox);
|
|
584
|
-
} catch (error) {
|
|
585
|
-
logException(error, "agent.plugin.after_tool_execute.failed", { "gen_ai.tool.name": args.tool.name });
|
|
586
|
-
return [];
|
|
587
|
-
}
|
|
588
|
-
const nudges = [];
|
|
589
|
-
for (const plugin of hooked) {
|
|
590
|
-
if (signal?.aborted) break;
|
|
591
|
-
const pluginName = plugin.manifest.name;
|
|
592
|
-
const onCost = createPluginModelCostRecorder({
|
|
593
|
-
...args.turn,
|
|
594
|
-
pluginName,
|
|
595
|
-
source: "afterToolExecute",
|
|
596
|
-
toolName: args.tool.name
|
|
597
|
-
});
|
|
598
|
-
let denial;
|
|
599
|
-
try {
|
|
600
|
-
await withPluginHookSpan(pluginName, "afterToolExecute", async () => await plugin.hooks.afterToolExecute({
|
|
601
|
-
...basePluginContext(plugin),
|
|
602
|
-
decider: createPluginDecider(pluginName, {
|
|
603
|
-
onCost,
|
|
604
|
-
signal
|
|
605
|
-
}),
|
|
606
|
-
decision: {
|
|
607
|
-
deny(reason) {
|
|
608
|
-
denial = reason;
|
|
609
|
-
},
|
|
610
|
-
nudge(message) {
|
|
611
|
-
nudges.push({
|
|
612
|
-
message,
|
|
613
|
-
pluginName
|
|
614
|
-
});
|
|
615
|
-
}
|
|
616
|
-
},
|
|
617
|
-
model: createPluginModel(pluginName, plugin.model, {
|
|
618
|
-
onCost,
|
|
619
|
-
signal
|
|
620
|
-
}),
|
|
621
|
-
sandbox,
|
|
622
|
-
...signal ? { signal } : void 0,
|
|
623
|
-
tool: {
|
|
624
|
-
input: args.tool.input,
|
|
625
|
-
name: args.tool.name
|
|
626
|
-
},
|
|
627
|
-
...workspace ? { workspace } : void 0
|
|
628
|
-
}));
|
|
629
|
-
} catch (error) {
|
|
630
|
-
if (signal?.aborted) break;
|
|
631
|
-
const attributes = {
|
|
632
|
-
"app.plugin.name": pluginName,
|
|
633
|
-
"gen_ai.tool.name": args.tool.name
|
|
634
|
-
};
|
|
635
|
-
if (isToolInputError(error)) logWarn("agent.plugin.after_tool_execute.failed", {
|
|
636
|
-
...attributes,
|
|
637
|
-
"error.type": "tool_input_error"
|
|
638
|
-
});
|
|
639
|
-
else logException(error, "agent.plugin.after_tool_execute.failed", attributes);
|
|
640
|
-
continue;
|
|
641
|
-
}
|
|
642
|
-
if (denial !== void 0) throw new PluginToolDeniedError(denial, { ran: true });
|
|
643
|
-
}
|
|
644
|
-
return nudges;
|
|
645
|
-
}
|
|
646
|
-
// src/chat/plugins/hooks/runner.ts
|
|
647
|
-
function normalizeEnv(value) {
|
|
648
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
|
|
649
|
-
const env = {};
|
|
650
|
-
for (const [key, rawValue] of Object.entries(value)) if (typeof rawValue === "string") env[key] = rawValue;
|
|
651
|
-
return env;
|
|
652
|
-
}
|
|
653
|
-
/** Create one runner over runtime hook plugins registered by the app. */
|
|
654
|
-
function createPluginHookRunner(input = {}) {
|
|
655
|
-
const loaded = getRegistrations();
|
|
656
|
-
return {
|
|
657
|
-
async afterToolExecute(tool) {
|
|
658
|
-
if (!input.toolRun) return [];
|
|
659
|
-
const { sandbox, ...turn } = input.toolRun;
|
|
660
|
-
return await runAfterToolExecuteHooks({
|
|
661
|
-
plugins: loaded,
|
|
662
|
-
sandbox: sandbox(),
|
|
663
|
-
tool,
|
|
664
|
-
turn
|
|
665
|
-
});
|
|
666
|
-
},
|
|
667
|
-
async afterMcpTool(tool) {
|
|
668
|
-
const cards = [];
|
|
669
|
-
for (const plugin of loaded) {
|
|
670
|
-
if (plugin.manifest.name !== tool.provider) continue;
|
|
671
|
-
const hook = plugin.hooks?.afterMcpTool;
|
|
672
|
-
if (!hook) continue;
|
|
673
|
-
const annotations = tool.conversationId ? createPluginAnnotations({
|
|
674
|
-
conversationId: tool.conversationId,
|
|
675
|
-
db: getDb(),
|
|
676
|
-
plugin: plugin.manifest.name
|
|
677
|
-
}) : void 0;
|
|
678
|
-
try {
|
|
679
|
-
const result = await hook({
|
|
680
|
-
...basePluginContext(plugin),
|
|
681
|
-
...tool.conversationId ? { conversationId: tool.conversationId } : void 0,
|
|
682
|
-
...annotations ? { annotations } : void 0,
|
|
683
|
-
result: {
|
|
684
|
-
content: tool.content,
|
|
685
|
-
structuredContent: tool.structuredContent
|
|
686
|
-
},
|
|
687
|
-
tool: {
|
|
688
|
-
arguments: tool.arguments,
|
|
689
|
-
name: tool.toolName
|
|
690
|
-
}
|
|
691
|
-
});
|
|
692
|
-
if (result && tool.conversationId) cards.push(...await saveObjectAnnotations(tool.conversationId, plugin.manifest.name, result.objectAnnotations));
|
|
693
|
-
} catch (error) {
|
|
694
|
-
logWarn("agent.plugin.after_mcp_tool.failed", {
|
|
695
|
-
"app.plugin.name": plugin.manifest.name,
|
|
696
|
-
"gen_ai.tool.name": tool.toolName,
|
|
697
|
-
"exception.message": error instanceof Error ? error.message : String(error)
|
|
698
|
-
});
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
return cards;
|
|
702
|
-
},
|
|
703
|
-
async prepareWorkspace(sandbox, repos, signal) {
|
|
704
|
-
const preparers = new Set(loaded.filter((plugin) => plugin.hooks?.workspacePrepare).map((plugin) => plugin.manifest.name));
|
|
705
|
-
const unhandledProviders = [...new Set(repos.map((repo) => repo.provider).filter((provider) => !preparers.has(provider)))].sort();
|
|
706
|
-
if (unhandledProviders.length > 0) throw new Error(`Workspace repository providers have no preparation hook: ${unhandledProviders.join(", ")}`);
|
|
707
|
-
const selectedRepos = repos.map((repo) => ({
|
|
708
|
-
provider: repo.provider,
|
|
709
|
-
repo: repo.repo,
|
|
710
|
-
path: workspaceRepoCheckoutPath(repo.repo)
|
|
711
|
-
}));
|
|
712
|
-
const paths = /* @__PURE__ */ new Set();
|
|
713
|
-
for (const entry of selectedRepos) {
|
|
714
|
-
const key = entry.path.toLowerCase();
|
|
715
|
-
if (paths.has(key)) throw new Error(`Workspace checkout path collision: ${entry.path}`);
|
|
716
|
-
paths.add(key);
|
|
717
|
-
}
|
|
718
|
-
const sandboxCapability = createSandboxCapability(sandbox, signal);
|
|
719
|
-
const finalizers = [];
|
|
720
|
-
for (const plugin of loaded) {
|
|
721
|
-
const hook = plugin.hooks?.workspacePrepare;
|
|
722
|
-
if (!hook) continue;
|
|
723
|
-
const selected = selectedRepos.filter((repo) => repo.provider === plugin.manifest.name).map((repo) => ({
|
|
724
|
-
path: repo.path,
|
|
725
|
-
repo: repo.repo
|
|
726
|
-
}));
|
|
727
|
-
if (selected.length === 0) continue;
|
|
728
|
-
const finalize = await hook({
|
|
729
|
-
...basePluginContext(plugin),
|
|
730
|
-
repos: selected,
|
|
731
|
-
sandbox: sandboxCapability
|
|
732
|
-
});
|
|
733
|
-
if (finalize) finalizers.push(finalize);
|
|
734
|
-
}
|
|
735
|
-
return async () => {
|
|
736
|
-
for (const finalize of finalizers) await finalize();
|
|
737
|
-
};
|
|
738
|
-
},
|
|
739
|
-
async prepareSandbox(sandbox) {
|
|
740
|
-
const sandboxCapability = createSandboxCapability(sandbox);
|
|
741
|
-
for (const plugin of loaded) {
|
|
742
|
-
const pluginName = plugin.manifest.name;
|
|
743
|
-
const hook = plugin.hooks?.sandboxPrepare;
|
|
744
|
-
if (!hook) continue;
|
|
745
|
-
logInfo("agent.plugin.sandbox_preparation.started", { "app.plugin.name": pluginName });
|
|
746
|
-
await withPluginHookSpan(pluginName, "sandboxPrepare", async () => await hook({
|
|
747
|
-
...basePluginContext(plugin),
|
|
748
|
-
actor: input.actor,
|
|
749
|
-
sandbox: sandboxCapability
|
|
750
|
-
}));
|
|
751
|
-
}
|
|
752
|
-
},
|
|
753
|
-
async beforeToolExecute(tool) {
|
|
754
|
-
const env = {};
|
|
755
|
-
let nextInput = { ...tool.input };
|
|
756
|
-
const actors = input.actors?.() ?? (input.actor ? [input.actor] : []);
|
|
757
|
-
for (const plugin of loaded) {
|
|
758
|
-
const pluginName = plugin.manifest.name;
|
|
759
|
-
const hook = plugin.hooks?.beforeToolExecute;
|
|
760
|
-
if (!hook) continue;
|
|
761
|
-
let replacement;
|
|
762
|
-
let blocked;
|
|
763
|
-
await withPluginHookSpan(pluginName, "beforeToolExecute", async () => await hook({
|
|
764
|
-
...basePluginContext(plugin),
|
|
765
|
-
actor: input.actor,
|
|
766
|
-
actors,
|
|
767
|
-
tool: {
|
|
768
|
-
name: tool.name,
|
|
769
|
-
input: nextInput
|
|
770
|
-
},
|
|
771
|
-
users: { resolveActor: async () => input.actor ? await readActorIdentity(input.actor) : void 0 },
|
|
772
|
-
juniorRoot: SANDBOX_JUNIOR_ROOT,
|
|
773
|
-
env: {
|
|
774
|
-
get(key) {
|
|
775
|
-
return env[key] ?? normalizeEnv(nextInput["env"])[key];
|
|
776
|
-
},
|
|
777
|
-
set(key, value) {
|
|
778
|
-
env[key] = value;
|
|
779
|
-
}
|
|
780
|
-
},
|
|
781
|
-
decision: {
|
|
782
|
-
deny(reason) {
|
|
783
|
-
blocked = new PluginToolDeniedError(reason);
|
|
784
|
-
},
|
|
785
|
-
redirect(message) {
|
|
786
|
-
blocked = new ToolInputError(message);
|
|
787
|
-
},
|
|
788
|
-
replaceInput(input) {
|
|
789
|
-
replacement = input;
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
}));
|
|
793
|
-
if (blocked) throw blocked;
|
|
794
|
-
if (replacement !== void 0) {
|
|
795
|
-
if (typeof replacement !== "object" || replacement === null || Array.isArray(replacement)) throw new Error(`Plugin "${pluginName}" replaced tool input with a non-object value`);
|
|
796
|
-
nextInput = { ...replacement };
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
return {
|
|
800
|
-
input: nextInput,
|
|
801
|
-
env
|
|
802
|
-
};
|
|
803
|
-
}
|
|
804
|
-
};
|
|
805
|
-
}
|
|
806
|
-
// src/chat/events/ingest.ts
|
|
807
|
-
/** Match a normalized event and enqueue notifications into conversations. */
|
|
808
|
-
async function ingestEvent(input, options) {
|
|
809
|
-
const event = eventSchema.parse(input);
|
|
810
|
-
const nowMs = options.nowMs ?? Date.now();
|
|
811
|
-
const subscriptions = await findMatchingWatches({
|
|
812
|
-
data: event.data,
|
|
813
|
-
eventType: event.eventType,
|
|
814
|
-
nowMs,
|
|
815
|
-
namespace: event.namespace,
|
|
816
|
-
identifier: event.identifier,
|
|
817
|
-
state: options.state
|
|
818
|
-
});
|
|
819
|
-
if (subscriptions.length === 0) return { enqueued: 0 };
|
|
820
|
-
const author = await resolveEventAuthor(event);
|
|
821
|
-
if (author.status === "untrusted") logInfo("event.author.untrusted", {
|
|
822
|
-
"app.event.event_type": event.eventType,
|
|
823
|
-
"app.event.namespace": event.namespace,
|
|
824
|
-
"app.event.author.reason": author.reason
|
|
825
|
-
});
|
|
826
|
-
let people = [];
|
|
827
|
-
if (options.slackTeamId && event.people?.length) try {
|
|
828
|
-
people = await resolveEventMentions(event.people, options.slackTeamId);
|
|
829
|
-
} catch (error) {
|
|
830
|
-
logException(error, "event.people.resolve.failed", {
|
|
831
|
-
"app.event.event_type": event.eventType,
|
|
832
|
-
"app.event.namespace": event.namespace
|
|
833
|
-
});
|
|
834
|
-
}
|
|
835
|
-
const doneBy = author.status === "trusted" && author.actor ? {
|
|
836
|
-
mention: slackMention(author.actor.userId),
|
|
837
|
-
handle: author.handle
|
|
838
|
-
} : void 0;
|
|
839
|
-
const turnConversations = /* @__PURE__ */ new Set();
|
|
840
|
-
const ordered = [...subscriptions].sort((left, right) => Number(isQuietEvent(left, event.eventType)) - Number(isQuietEvent(right, event.eventType)));
|
|
841
|
-
let enqueued = 0;
|
|
842
|
-
const errors = [];
|
|
843
|
-
const waitDeadlineMs = Date.now() + 1e4;
|
|
844
|
-
for (const subscription of ordered) {
|
|
845
|
-
let quiet = false;
|
|
846
|
-
try {
|
|
847
|
-
if (await deliverWatch({
|
|
848
|
-
data: event.data,
|
|
849
|
-
eventType: event.eventType,
|
|
850
|
-
namespace: event.namespace,
|
|
851
|
-
identifier: event.identifier,
|
|
852
|
-
terminal: event.terminal,
|
|
853
|
-
nowMs,
|
|
854
|
-
state: options.state,
|
|
855
|
-
subscription,
|
|
856
|
-
waitDeadlineMs,
|
|
857
|
-
deliver: async (current) => {
|
|
858
|
-
if (options.admit && !await options.admit(current)) return false;
|
|
859
|
-
if (isQuietEvent(current, event.eventType)) {
|
|
860
|
-
quiet = true;
|
|
861
|
-
if (!turnConversations.has(current.conversationId)) await addQuietEventNote({
|
|
862
|
-
event,
|
|
863
|
-
subscription: current
|
|
864
|
-
});
|
|
865
|
-
return true;
|
|
866
|
-
}
|
|
867
|
-
const result = await enqueueEventNotification({
|
|
868
|
-
author,
|
|
869
|
-
doneBy,
|
|
870
|
-
event,
|
|
871
|
-
people,
|
|
872
|
-
queue: options.queue,
|
|
873
|
-
state: options.state,
|
|
874
|
-
subscription: current
|
|
875
|
-
});
|
|
876
|
-
if (result.status === "held") return false;
|
|
877
|
-
turnConversations.add(current.conversationId);
|
|
878
|
-
return result.status === "appended";
|
|
879
|
-
}
|
|
880
|
-
}) && !quiet) enqueued += 1;
|
|
881
|
-
} catch (error) {
|
|
882
|
-
errors.push(error);
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
if (errors.length > 0) throw new AggregateError(errors, "Failed to deliver one or more watches");
|
|
886
|
-
return { enqueued };
|
|
887
|
-
}
|
|
888
|
-
// src/chat/sandbox/prepare-workspace.ts
|
|
889
|
-
const WORKSPACE_SETUP_FAILURE_OUTPUT_MAX_CHARS = 7e3;
|
|
890
|
-
const WORKSPACE_SETUP_FAILURE_TRUNCATION_MARKER = "[earlier setup output truncated]\n";
|
|
891
|
-
const WORKSPACE_SETUP_NODE_OPTIONS = "--max-old-space-size=4096";
|
|
892
|
-
/** Prepare repositories before a Workspace setup script starts. */
|
|
893
|
-
async function prepareWorkspaceRepositories(params) {
|
|
894
|
-
const { sandbox, workspace, signal } = params;
|
|
895
|
-
signal?.throwIfAborted();
|
|
896
|
-
await params.applyNetworkPolicy(sandbox);
|
|
897
|
-
const finalize = await params.prepareRepositories?.(sandbox, workspace, signal);
|
|
898
|
-
if (params.removeCredentialRoute) await sandbox.update({ networkPolicy: "allow-all" });
|
|
899
|
-
await finalize?.();
|
|
900
|
-
}
|
|
901
|
-
/** Return bounded setup output for a Workspace failure. */
|
|
902
|
-
function workspaceSetupFailureDetail(input) {
|
|
903
|
-
const output = [input.stdout.trim() ? `stdout:\n${input.stdout.trim()}` : "", input.stderr.trim() ? `stderr:\n${input.stderr.trim()}` : ""].filter(Boolean).join("\n\n");
|
|
904
|
-
if (!output) return `exit ${input.exitCode}`;
|
|
905
|
-
if (output.length <= WORKSPACE_SETUP_FAILURE_OUTPUT_MAX_CHARS) return output;
|
|
906
|
-
return `${WORKSPACE_SETUP_FAILURE_TRUNCATION_MARKER}${output.slice(-6967)}`;
|
|
907
|
-
}
|
|
908
|
-
/** Build the env vars shared by every Workspace setup command. */
|
|
909
|
-
function workspaceSetupEnv() {
|
|
910
|
-
return {
|
|
911
|
-
JUNIOR_REPOS_ROOT: SANDBOX_REPOS_ROOT,
|
|
912
|
-
JUNIOR_WORKSPACE_ROOT: SANDBOX_WORKSPACE_ROOT,
|
|
913
|
-
NODE_OPTIONS: WORKSPACE_SETUP_NODE_OPTIONS
|
|
914
|
-
};
|
|
915
|
-
}
|
|
916
|
-
/** Build the command for one Workspace setup script. */
|
|
917
|
-
function workspaceSetupCommand(workspace) {
|
|
918
|
-
return {
|
|
919
|
-
cmd: "bash",
|
|
920
|
-
args: [
|
|
921
|
-
"-euo",
|
|
922
|
-
"pipefail",
|
|
923
|
-
"-c",
|
|
924
|
-
workspace.setupScript
|
|
925
|
-
],
|
|
926
|
-
cwd: SANDBOX_WORKSPACE_ROOT,
|
|
927
|
-
env: workspaceSetupEnv()
|
|
928
|
-
};
|
|
929
|
-
}
|
|
930
|
-
/** Build a restart-safe command for one Workspace snapshot setup script. */
|
|
931
|
-
function workspaceSnapshotSetupCommand(workspace, buildId) {
|
|
932
|
-
const stateRoot = `/tmp/junior-snapshot-build-${buildId}`;
|
|
933
|
-
return {
|
|
934
|
-
cmd: "bash",
|
|
935
|
-
args: [
|
|
936
|
-
"-euo",
|
|
937
|
-
"pipefail",
|
|
938
|
-
"-c",
|
|
939
|
-
[
|
|
940
|
-
`mkdir -p "${stateRoot}"`,
|
|
941
|
-
`exec 9>"${stateRoot}/lock"`,
|
|
942
|
-
"flock 9",
|
|
943
|
-
`if test -f "${stateRoot}/exit"; then exit "$(cat "${stateRoot}/exit")"; fi`,
|
|
944
|
-
"set +e",
|
|
945
|
-
"bash -euo pipefail -c \"$1\"",
|
|
946
|
-
"status=$?",
|
|
947
|
-
`printf '%s\\n' "$status" > "${stateRoot}/exit"`,
|
|
948
|
-
"exit \"$status\""
|
|
949
|
-
].join("\n"),
|
|
950
|
-
"junior-setup",
|
|
951
|
-
workspace.setupScript
|
|
952
|
-
],
|
|
953
|
-
cwd: SANDBOX_WORKSPACE_ROOT,
|
|
954
|
-
env: workspaceSetupEnv()
|
|
955
|
-
};
|
|
956
|
-
}
|
|
957
|
-
/** Prepare repositories and setup state before a Workspace snapshot is captured. */
|
|
958
|
-
async function prepareWorkspaceSnapshot(params) {
|
|
959
|
-
const { sandbox, workspace, signal } = params;
|
|
960
|
-
await prepareWorkspaceRepositories(params);
|
|
961
|
-
if (!workspace.setupScript.trim()) return;
|
|
962
|
-
const result = await sandbox.runCommand({
|
|
963
|
-
...workspaceSetupCommand(workspace),
|
|
964
|
-
signal
|
|
965
|
-
});
|
|
966
|
-
if (result.exitCode !== 0) throw new Error(`Workspace setup failed: ${workspaceSetupFailureDetail(result)}`);
|
|
967
|
-
}
|
|
968
|
-
// src/chat/sandbox/snapshot/workspace.ts
|
|
969
|
-
const BUILD_TIMEOUT_MS = 36e5;
|
|
970
|
-
const BUILD_TIMEOUT_ERROR = "Workspace snapshot build timed out after 1 hour";
|
|
971
|
-
const BUILD_LOCK_TTL_MS = 12e4;
|
|
972
|
-
const BUILD_LOCK_PREFIX = "junior:workspace_snapshot_start";
|
|
973
|
-
const WAIT_POLL_MS = 5e3;
|
|
974
|
-
const TRANSIENT_API_RETRY_MS = 2e3;
|
|
975
|
-
const BUILD_COMMAND_TIMEOUT_MS = 6e5;
|
|
976
|
-
const BUILD_COMMAND_TIMEOUT_ERROR = "Workspace snapshot build phase timed out after 10 minutes";
|
|
977
|
-
const COMMAND_STATUS_POLL_TIMEOUT_MS = 1e3;
|
|
978
|
-
/** Leave time to save the build state before this request ends. */
|
|
979
|
-
const STOP_BUFFER_MS = 4e4;
|
|
980
|
-
/** Keep the build open when a request stops or the provider has a short failure. */
|
|
981
|
-
function isCancelOrTransient(error) {
|
|
982
|
-
return isAbortError(error) || getSandboxProvider().errors.isTransient(error);
|
|
983
|
-
}
|
|
984
|
-
function buildLockKey(profileHash) {
|
|
985
|
-
return `${BUILD_LOCK_PREFIX}:${profileHash}`;
|
|
986
|
-
}
|
|
987
|
-
function builderName() {
|
|
988
|
-
return `junior-ws-${randomUUID()}`;
|
|
989
|
-
}
|
|
990
|
-
async function snapshotFromSql(workspaceId, value, staleSnapshotId) {
|
|
991
|
-
const { ready } = await loadSnapshotsForProfile(getDb(), workspaceId, value.hash);
|
|
992
|
-
if (!ready) return null;
|
|
993
|
-
if (ready.id === staleSnapshotId || isStale(value, ready.generatedAt.getTime())) {
|
|
994
|
-
const ownerName = await invalidateReadySnapshot({
|
|
995
|
-
workspaceId,
|
|
996
|
-
profileHash: value.hash,
|
|
997
|
-
snapshotId: ready.id
|
|
998
|
-
});
|
|
999
|
-
try {
|
|
1000
|
-
await deleteBuilder(ownerName);
|
|
1001
|
-
} catch (error) {
|
|
1002
|
-
logException(error, "sandbox.workspace_snapshot.builder.delete_failed", { "app.workspace.id": workspaceId });
|
|
1003
|
-
}
|
|
1004
|
-
return null;
|
|
1005
|
-
}
|
|
1006
|
-
return {
|
|
1007
|
-
snapshotId: ready.id,
|
|
1008
|
-
profileHash: ready.profileHash,
|
|
1009
|
-
dependencyCount: value.dependencyCount,
|
|
1010
|
-
cacheHit: true,
|
|
1011
|
-
resolveOutcome: "cache_hit",
|
|
1012
|
-
createdAtMs: ready.generatedAt.getTime(),
|
|
1013
|
-
buildDurationMs: ready.buildDurationMs
|
|
1014
|
-
};
|
|
1015
|
-
}
|
|
1016
|
-
/** Return a build only when it has enough saved state to continue. */
|
|
1017
|
-
function activeBuild(build) {
|
|
1018
|
-
if (!build || build.status !== "building" || !build.sandboxName) return null;
|
|
1019
|
-
return build;
|
|
1020
|
-
}
|
|
1021
|
-
async function deleteBuilder(sandboxName) {
|
|
1022
|
-
if (!sandboxName) return;
|
|
1023
|
-
await getSandboxProvider().deleteWorkspaceSnapshotBuilders([sandboxName]);
|
|
1024
|
-
}
|
|
1025
|
-
function workspaceDeletedError(workspace) {
|
|
1026
|
-
return /* @__PURE__ */ new Error(`Workspace ${workspace.name} was deleted while its snapshot was building`);
|
|
1027
|
-
}
|
|
1028
|
-
function requireBuildWrite(written, workspace) {
|
|
1029
|
-
if (!written) throw new Error(`Workspace ${workspace.name} snapshot build lost SQL ownership`);
|
|
1030
|
-
}
|
|
1031
|
-
/** Save a build failure, then delete its Sandbox. */
|
|
1032
|
-
async function markFailed(workspace, build, error, beforeWrite) {
|
|
1033
|
-
try {
|
|
1034
|
-
await beforeWrite();
|
|
1035
|
-
requireBuildWrite(await setWorkspaceSnapshotBuild(workspace.id, {
|
|
1036
|
-
...build,
|
|
1037
|
-
status: "failed",
|
|
1038
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1039
|
-
}), workspace);
|
|
1040
|
-
} catch (persistError) {
|
|
1041
|
-
logException(persistError, "sandbox.workspace_snapshot.failure_persist_failed", { "app.workspace.id": workspace.id });
|
|
1042
|
-
return;
|
|
1043
|
-
}
|
|
1044
|
-
try {
|
|
1045
|
-
await deleteBuilder(build.sandboxName);
|
|
1046
|
-
} catch (cleanupError) {
|
|
1047
|
-
logException(cleanupError, "sandbox.workspace_snapshot.builder.delete_failed", { "app.workspace.id": workspace.id });
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
/** Stop a build after one hour. */
|
|
1051
|
-
async function requireRemainingBuildTime(workspace, build, beforeWrite) {
|
|
1052
|
-
const remainingMs = build.startedAt.getTime() + BUILD_TIMEOUT_MS - Date.now();
|
|
1053
|
-
if (remainingMs > 0) return remainingMs;
|
|
1054
|
-
await markFailed(workspace, build, BUILD_TIMEOUT_ERROR, beforeWrite);
|
|
1055
|
-
throw new Error(BUILD_TIMEOUT_ERROR);
|
|
1056
|
-
}
|
|
1057
|
-
/** Save the snapshot when its setup command ends. */
|
|
1058
|
-
async function finishBuild(workspace, value, signal, beforeWrite) {
|
|
1059
|
-
const { build: loaded } = await loadSnapshotsForProfile(getDb(), workspace.id, value.hash);
|
|
1060
|
-
const build = activeBuild(loaded);
|
|
1061
|
-
if (!build?.commandId || !build.sandboxName) return null;
|
|
1062
|
-
try {
|
|
1063
|
-
await requireRemainingBuildTime(workspace, build, beforeWrite);
|
|
1064
|
-
const builder = await getSandboxProvider().getWorkspaceSnapshotBuilder(build.sandboxName, signal);
|
|
1065
|
-
const command = await builder.getCommand(build.commandId, { signal });
|
|
1066
|
-
const pollSignal = AbortSignal.timeout(COMMAND_STATUS_POLL_TIMEOUT_MS);
|
|
1067
|
-
const waitSignal = signal ? AbortSignal.any([signal, pollSignal]) : pollSignal;
|
|
1068
|
-
let finished;
|
|
1069
|
-
try {
|
|
1070
|
-
finished = await command.wait({ signal: waitSignal });
|
|
1071
|
-
} catch (error) {
|
|
1072
|
-
if (pollSignal.aborted && !signal?.aborted) return null;
|
|
1073
|
-
throw error;
|
|
1074
|
-
}
|
|
1075
|
-
if (finished.exitCode !== 0) {
|
|
1076
|
-
const [stdout, stderr] = await Promise.all([finished.stdout({ signal }), finished.stderr({ signal })]);
|
|
1077
|
-
const detail = workspaceSetupFailureDetail({
|
|
1078
|
-
exitCode: finished.exitCode,
|
|
1079
|
-
stdout,
|
|
1080
|
-
stderr
|
|
1081
|
-
});
|
|
1082
|
-
throw new Error(`Workspace ${workspace.name} snapshot setup failed: ${detail}`);
|
|
1083
|
-
}
|
|
1084
|
-
await requireRemainingBuildTime(workspace, build, beforeWrite);
|
|
1085
|
-
const snapshot = await builder.snapshot({ signal });
|
|
1086
|
-
await requireRemainingBuildTime(workspace, build, beforeWrite);
|
|
1087
|
-
const createdAtMs = Date.now();
|
|
1088
|
-
const buildDurationMs = Math.max(0, createdAtMs - build.startedAt.getTime());
|
|
1089
|
-
const sizeBytes = typeof snapshot.sizeBytes === "number" && Number.isFinite(snapshot.sizeBytes) && snapshot.sizeBytes >= 0 ? snapshot.sizeBytes : null;
|
|
1090
|
-
await beforeWrite();
|
|
1091
|
-
const result = await setWorkspaceSnapshot(workspace.id, {
|
|
1092
|
-
id: snapshot.snapshotId,
|
|
1093
|
-
generatedAt: new Date(createdAtMs),
|
|
1094
|
-
buildDurationMs,
|
|
1095
|
-
sizeBytes,
|
|
1096
|
-
profileHash: value.hash
|
|
1097
|
-
}, { buildId: build.id });
|
|
1098
|
-
requireBuildWrite(result.written, workspace);
|
|
1099
|
-
try {
|
|
1100
|
-
await getSandboxProvider().deleteWorkspaceSnapshotBuilders(result.replacedBuilderNames);
|
|
1101
|
-
} catch (error) {
|
|
1102
|
-
logException(error, "sandbox.workspace_snapshot.builder.delete_failed", {
|
|
1103
|
-
"app.workspace.id": workspace.id,
|
|
1104
|
-
"app.sandbox.snapshot.builder_count": result.replacedBuilderNames.length
|
|
1105
|
-
});
|
|
1106
|
-
}
|
|
1107
|
-
return {
|
|
1108
|
-
snapshotId: snapshot.snapshotId,
|
|
1109
|
-
profileHash: value.hash,
|
|
1110
|
-
dependencyCount: value.dependencyCount,
|
|
1111
|
-
cacheHit: false,
|
|
1112
|
-
resolveOutcome: "rebuilt",
|
|
1113
|
-
rebuildReason: "cache_miss",
|
|
1114
|
-
createdAtMs,
|
|
1115
|
-
buildDurationMs
|
|
1116
|
-
};
|
|
1117
|
-
} catch (error) {
|
|
1118
|
-
if (error instanceof Error && error.message === BUILD_TIMEOUT_ERROR) throw error;
|
|
1119
|
-
if (isCancelOrTransient(error)) throw error;
|
|
1120
|
-
await markFailed(workspace, build, error, beforeWrite);
|
|
1121
|
-
throw error;
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
/** Create the Sandbox and save its name. */
|
|
1125
|
-
async function startBuild(params) {
|
|
1126
|
-
const { workspace, value, signal } = params;
|
|
1127
|
-
const resources = getSandboxResources(workspace);
|
|
1128
|
-
const name = builderName();
|
|
1129
|
-
const buildId = randomUUID();
|
|
1130
|
-
const startedAt = /* @__PURE__ */ new Date();
|
|
1131
|
-
try {
|
|
1132
|
-
await getSandboxProvider().createWorkspaceSnapshotBuilder({
|
|
1133
|
-
name,
|
|
1134
|
-
runtime: params.runtime,
|
|
1135
|
-
timeoutMs: BUILD_TIMEOUT_MS,
|
|
1136
|
-
signal,
|
|
1137
|
-
...resources ? { resources } : void 0
|
|
1138
|
-
});
|
|
1139
|
-
await params.beforeWrite();
|
|
1140
|
-
if (!await setWorkspaceSnapshotBuild(workspace.id, {
|
|
1141
|
-
id: buildId,
|
|
1142
|
-
status: "building",
|
|
1143
|
-
phase: "created",
|
|
1144
|
-
profileHash: value.hash,
|
|
1145
|
-
startedAt,
|
|
1146
|
-
sandboxName: name,
|
|
1147
|
-
commandId: null,
|
|
1148
|
-
error: null
|
|
1149
|
-
}, {
|
|
1150
|
-
insertIfMissing: true,
|
|
1151
|
-
expectedRecipe: workspace
|
|
1152
|
-
})) {
|
|
1153
|
-
try {
|
|
1154
|
-
await deleteBuilder(name);
|
|
1155
|
-
} catch (cleanupError) {
|
|
1156
|
-
logException(cleanupError, "sandbox.workspace_snapshot.builder.delete_failed", { "app.workspace.id": workspace.id });
|
|
1157
|
-
}
|
|
1158
|
-
return;
|
|
1159
|
-
}
|
|
1160
|
-
} catch (error) {
|
|
1161
|
-
try {
|
|
1162
|
-
if (!isCancelOrTransient(error)) try {
|
|
1163
|
-
await params.beforeWrite();
|
|
1164
|
-
await setWorkspaceSnapshotBuild(workspace.id, {
|
|
1165
|
-
id: buildId,
|
|
1166
|
-
status: "failed",
|
|
1167
|
-
phase: "created",
|
|
1168
|
-
profileHash: value.hash,
|
|
1169
|
-
startedAt,
|
|
1170
|
-
sandboxName: name,
|
|
1171
|
-
commandId: null,
|
|
1172
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1173
|
-
}, {
|
|
1174
|
-
insertIfMissing: true,
|
|
1175
|
-
expectedRecipe: workspace
|
|
1176
|
-
});
|
|
1177
|
-
} catch {}
|
|
1178
|
-
} finally {
|
|
1179
|
-
try {
|
|
1180
|
-
await deleteBuilder(name);
|
|
1181
|
-
} catch (cleanupError) {
|
|
1182
|
-
logException(cleanupError, "sandbox.workspace_snapshot.builder.delete_failed", { "app.workspace.id": workspace.id });
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
throw error;
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
/** Complete one saved setup step in the build Sandbox. */
|
|
1189
|
-
async function continueBuild(params) {
|
|
1190
|
-
const { build: loaded } = await loadSnapshotsForProfile(getDb(), params.workspace.id, params.value.hash);
|
|
1191
|
-
const build = activeBuild(loaded);
|
|
1192
|
-
if (!build?.sandboxName || build.commandId) return;
|
|
1193
|
-
const remainingMs = await requireRemainingBuildTime(params.workspace, build, params.beforeWrite);
|
|
1194
|
-
const commandTimeoutMs = Math.min(remainingMs, BUILD_COMMAND_TIMEOUT_MS);
|
|
1195
|
-
const phaseTimeoutSignal = AbortSignal.timeout(commandTimeoutMs);
|
|
1196
|
-
const phaseSignal = params.signal ? AbortSignal.any([params.signal, phaseTimeoutSignal]) : phaseTimeoutSignal;
|
|
1197
|
-
try {
|
|
1198
|
-
const builder = await getSandboxProvider().getWorkspaceSnapshotBuilder(build.sandboxName, phaseSignal);
|
|
1199
|
-
const session = builder.session();
|
|
1200
|
-
if (build.phase === "created") {
|
|
1201
|
-
await dependencies(session, params.value.dependencies, phaseSignal, commandTimeoutMs);
|
|
1202
|
-
await postinstall(session, params.value.postinstall, phaseSignal, commandTimeoutMs);
|
|
1203
|
-
await requireRemainingBuildTime(params.workspace, build, params.beforeWrite);
|
|
1204
|
-
await params.beforeWrite();
|
|
1205
|
-
requireBuildWrite(await setWorkspaceSnapshotBuild(params.workspace.id, {
|
|
1206
|
-
...build,
|
|
1207
|
-
phase: "dependencies_installed"
|
|
1208
|
-
}), params.workspace);
|
|
1209
|
-
return;
|
|
1210
|
-
}
|
|
1211
|
-
if (build.phase === "dependencies_installed") {
|
|
1212
|
-
await prepareWorkspaceRepositories({
|
|
1213
|
-
sandbox: session,
|
|
1214
|
-
workspace: params.workspace,
|
|
1215
|
-
signal: phaseSignal,
|
|
1216
|
-
applyNetworkPolicy: params.applyNetworkPolicy,
|
|
1217
|
-
prepareRepositories: params.prepareRepositories,
|
|
1218
|
-
removeCredentialRoute: params.removeCredentialRoute
|
|
1219
|
-
});
|
|
1220
|
-
await requireRemainingBuildTime(params.workspace, build, params.beforeWrite);
|
|
1221
|
-
await params.beforeWrite();
|
|
1222
|
-
requireBuildWrite(await setWorkspaceSnapshotBuild(params.workspace.id, {
|
|
1223
|
-
...build,
|
|
1224
|
-
phase: "repositories_prepared"
|
|
1225
|
-
}), params.workspace);
|
|
1226
|
-
return;
|
|
1227
|
-
}
|
|
1228
|
-
await params.beforeWrite();
|
|
1229
|
-
const commandId = await builder.startDetachedCommand({
|
|
1230
|
-
...workspaceSnapshotSetupCommand(params.workspace, build.id),
|
|
1231
|
-
timeoutMs: remainingMs,
|
|
1232
|
-
signal: phaseSignal
|
|
1233
|
-
});
|
|
1234
|
-
await params.beforeWrite();
|
|
1235
|
-
requireBuildWrite(await setWorkspaceSnapshotBuild(params.workspace.id, {
|
|
1236
|
-
...build,
|
|
1237
|
-
commandId,
|
|
1238
|
-
error: null
|
|
1239
|
-
}), params.workspace);
|
|
1240
|
-
} catch (error) {
|
|
1241
|
-
if (phaseTimeoutSignal.aborted && !params.signal?.aborted) {
|
|
1242
|
-
const timeoutError = new Error(BUILD_COMMAND_TIMEOUT_ERROR, { cause: error });
|
|
1243
|
-
await markFailed(params.workspace, build, timeoutError, params.beforeWrite);
|
|
1244
|
-
throw timeoutError;
|
|
1245
|
-
}
|
|
1246
|
-
if (error instanceof Error && error.message === BUILD_TIMEOUT_ERROR) throw error;
|
|
1247
|
-
if (isCancelOrTransient(error)) throw error;
|
|
1248
|
-
await markFailed(params.workspace, build, error, params.beforeWrite);
|
|
1249
|
-
throw error;
|
|
1250
|
-
}
|
|
1251
|
-
}
|
|
1252
|
-
/** Use a ready snapshot or complete one saved build step. */
|
|
1253
|
-
async function advanceWorkspaceSnapshot(params) {
|
|
1254
|
-
const value = create(params.runtime, params.workspace);
|
|
1255
|
-
if (!value) throw new Error(`Workspace ${params.workspace.name} has no snapshot profile`);
|
|
1256
|
-
const sqlCached = await snapshotFromSql(params.workspace.id, value, params.staleSnapshotId);
|
|
1257
|
-
if (sqlCached) return sqlCached;
|
|
1258
|
-
const state = getStateAdapter();
|
|
1259
|
-
await state.connect();
|
|
1260
|
-
const locked = await withLock(state, buildLockKey(value.hash), async (lock) => {
|
|
1261
|
-
const workspace = await getWorkspace(getDb(), params.workspace.id);
|
|
1262
|
-
if (!workspace) throw workspaceDeletedError(params.workspace);
|
|
1263
|
-
const lockedValue = create(params.runtime, workspace) ?? value;
|
|
1264
|
-
if (lockedValue.hash !== value.hash) return null;
|
|
1265
|
-
const beforeWrite = async () => {
|
|
1266
|
-
await fenceLock(state, lock, BUILD_LOCK_TTL_MS);
|
|
1267
|
-
};
|
|
1268
|
-
const sqlInsideLock = await snapshotFromSql(workspace.id, lockedValue, params.staleSnapshotId);
|
|
1269
|
-
if (sqlInsideLock) return sqlInsideLock;
|
|
1270
|
-
const finished = await finishBuild(workspace, lockedValue, params.signal, beforeWrite);
|
|
1271
|
-
if (finished) return finished;
|
|
1272
|
-
const { build: loaded } = await loadSnapshotsForProfile(getDb(), workspace.id, lockedValue.hash);
|
|
1273
|
-
const build = activeBuild(loaded);
|
|
1274
|
-
if (build && !build.commandId) await continueBuild({
|
|
1275
|
-
...params,
|
|
1276
|
-
workspace,
|
|
1277
|
-
value: lockedValue,
|
|
1278
|
-
beforeWrite
|
|
1279
|
-
});
|
|
1280
|
-
else if (!build) {
|
|
1281
|
-
if (loaded?.sandboxName) try {
|
|
1282
|
-
await deleteBuilder(loaded.sandboxName);
|
|
1283
|
-
} catch (cleanupError) {
|
|
1284
|
-
logException(cleanupError, "sandbox.workspace_snapshot.builder.delete_failed", { "app.workspace.id": workspace.id });
|
|
1285
|
-
}
|
|
1286
|
-
await startBuild({
|
|
1287
|
-
workspace,
|
|
1288
|
-
value: lockedValue,
|
|
1289
|
-
runtime: params.runtime,
|
|
1290
|
-
signal: params.signal,
|
|
1291
|
-
beforeWrite
|
|
1292
|
-
});
|
|
1293
|
-
}
|
|
1294
|
-
return null;
|
|
1295
|
-
}, {
|
|
1296
|
-
ttlMs: BUILD_LOCK_TTL_MS,
|
|
1297
|
-
keepAlive: true
|
|
1298
|
-
});
|
|
1299
|
-
return locked.acquired ? locked.value ?? null : null;
|
|
1300
|
-
}
|
|
1301
|
-
/** Check whether this request must stop soon. */
|
|
1302
|
-
function shouldStopForTimeLimit(shouldStop) {
|
|
1303
|
-
if (shouldStop?.()) return true;
|
|
1304
|
-
const deadlineAtMs = getTurnRequestDeadline()?.deadlineAtMs;
|
|
1305
|
-
return deadlineAtMs !== void 0 && Date.now() >= deadlineAtMs - STOP_BUFFER_MS;
|
|
1306
|
-
}
|
|
1307
|
-
/** Return the ready snapshot or report that the Workspace must build one. */
|
|
1308
|
-
async function requireReadyWorkspaceSnapshot(params) {
|
|
1309
|
-
const value = create(params.runtime, params.workspace);
|
|
1310
|
-
if (!value) throw new Error(`Workspace ${params.workspace.name} has no snapshot profile`);
|
|
1311
|
-
const snapshot = await snapshotFromSql(params.workspace.id, value, params.staleSnapshotId);
|
|
1312
|
-
if (!snapshot) throw new WorkspaceSnapshotNotReadyError(params.workspace.name);
|
|
1313
|
-
return snapshot;
|
|
1314
|
-
}
|
|
1315
|
-
/**
|
|
1316
|
-
* Continue a Workspace snapshot build from its saved state.
|
|
1317
|
-
* The full build can run for up to one hour.
|
|
1318
|
-
*/
|
|
1319
|
-
async function resolveWorkspaceSnapshot(params) {
|
|
1320
|
-
let advanced = false;
|
|
1321
|
-
for (;;) {
|
|
1322
|
-
params.signal?.throwIfAborted();
|
|
1323
|
-
const workspace = await getWorkspace(getDb(), params.workspace.id);
|
|
1324
|
-
if (!workspace) throw workspaceDeletedError(params.workspace);
|
|
1325
|
-
const current = {
|
|
1326
|
-
...params,
|
|
1327
|
-
workspace
|
|
1328
|
-
};
|
|
1329
|
-
if (advanced && shouldStopForTimeLimit(current.shouldStop)) throw new WorkspaceSnapshotNotReadyError(workspace.name);
|
|
1330
|
-
let snapshot;
|
|
1331
|
-
try {
|
|
1332
|
-
snapshot = await advanceWorkspaceSnapshot(current);
|
|
1333
|
-
} catch (error) {
|
|
1334
|
-
if (!getSandboxProvider().errors.isTransient(error)) throw error;
|
|
1335
|
-
advanced = true;
|
|
1336
|
-
if (shouldStopForTimeLimit(current.shouldStop)) throw new WorkspaceSnapshotNotReadyError(workspace.name);
|
|
1337
|
-
await sleep(TRANSIENT_API_RETRY_MS, params.signal);
|
|
1338
|
-
continue;
|
|
1339
|
-
}
|
|
1340
|
-
advanced = true;
|
|
1341
|
-
if (snapshot) return snapshot;
|
|
1342
|
-
if (shouldStopForTimeLimit(current.shouldStop)) throw new WorkspaceSnapshotNotReadyError(workspace.name);
|
|
1343
|
-
await sleep(WAIT_POLL_MS, params.signal);
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
// src/chat/sandbox/snapshot/job-queue.ts
|
|
1347
|
-
/** Send Workspace snapshot build messages. */
|
|
1348
|
-
const workspaceSnapshotJobSign = {
|
|
1349
|
-
context: "junior.workspace_snapshot_queue.v1",
|
|
1350
|
-
schema: z.object({
|
|
1351
|
-
workspaceId: z.string().uuid(),
|
|
1352
|
-
profileHash: z.string().min(1)
|
|
1353
|
-
}).strict(),
|
|
1354
|
-
signatureVersion: "v1",
|
|
1355
|
-
parts: (message) => [message.workspaceId, message.profileHash]
|
|
1356
|
-
};
|
|
1357
|
-
function jobId(message) {
|
|
1358
|
-
return `workspace-snapshot_${createHash("sha256").update(message.workspaceId).update("\0").update(message.profileHash).digest("hex").slice(0, 32)}`;
|
|
1359
|
-
}
|
|
1360
|
-
/** Sign a Workspace snapshot job for tests and local checks. */
|
|
1361
|
-
function signWorkspaceSnapshotJobMessage(message, nowMs = Date.now()) {
|
|
1362
|
-
return signQueueMessage(workspaceSnapshotJobSign, message, nowMs);
|
|
1363
|
-
}
|
|
1364
|
-
/** Check that a recent queue message came from Junior. */
|
|
1365
|
-
function verifyWorkspaceSnapshotJobMessage(value, nowMs = Date.now()) {
|
|
1366
|
-
return verifyQueueMessage(workspaceSnapshotJobSign, value, nowMs);
|
|
1367
|
-
}
|
|
1368
|
-
async function send(message, idempotencyKey) {
|
|
1369
|
-
const options = { retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3 };
|
|
1370
|
-
if (idempotencyKey) options.idempotencyKey = idempotencyKey;
|
|
1371
|
-
await getQueueProvider().send(WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, signWorkspaceSnapshotJobMessage(message), options);
|
|
1372
|
-
}
|
|
1373
|
-
/** Send a job unless the same Workspace build already has one. */
|
|
1374
|
-
async function sendWorkspaceSnapshotJob(message) {
|
|
1375
|
-
await send(message, jobId(message));
|
|
1376
|
-
}
|
|
1377
|
-
/** Send the next job for a Workspace build that is still running. */
|
|
1378
|
-
async function sendNextWorkspaceSnapshotJob(message) {
|
|
1379
|
-
await send(message);
|
|
1380
|
-
}
|
|
1381
|
-
// src/chat/sandbox/snapshot/job-runner.ts
|
|
1382
|
-
/** Build Workspace snapshots in a background job. */
|
|
1383
|
-
const SNAPSHOT_BUILD_SYSTEM_ACTOR = {
|
|
1384
|
-
platform: "system",
|
|
1385
|
-
name: "workspace-snapshot"
|
|
1386
|
-
};
|
|
1387
|
-
/** Leave time to send the next job before this request ends. */
|
|
1388
|
-
const JOB_STOP_BUFFER_MS = 4e4;
|
|
1389
|
-
async function publishFinishedEvent(input) {
|
|
1390
|
-
await ingestEvent(workspaceSnapshotFinishedEvent(input), { queue: getVercelConversationWorkQueue() });
|
|
1391
|
-
}
|
|
1392
|
-
function createSnapshotBuildHelpers() {
|
|
1393
|
-
const credentials = credentialContextForActor(SNAPSHOT_BUILD_SYSTEM_ACTOR);
|
|
1394
|
-
const pluginHooks = createPluginHookRunner();
|
|
1395
|
-
const applyNetworkPolicy = async (sandbox) => {
|
|
1396
|
-
const networkPolicy = buildSandboxEgressNetworkPolicy({ credentialToken: createSandboxEgressCredentialToken({
|
|
1397
|
-
credentials,
|
|
1398
|
-
egressId: sandbox.sessionId,
|
|
1399
|
-
ttlMs: 36e5
|
|
1400
|
-
}) });
|
|
1401
|
-
await sandbox.update({ networkPolicy });
|
|
1402
|
-
return networkPolicy;
|
|
1403
|
-
};
|
|
1404
|
-
const prepareRepositories = async (sandbox, target, signal) => await pluginHooks.prepareWorkspace(sandbox, target.repos, signal);
|
|
1405
|
-
return {
|
|
1406
|
-
applyNetworkPolicy,
|
|
1407
|
-
prepareRepositories
|
|
1408
|
-
};
|
|
1409
|
-
}
|
|
1410
|
-
function shouldStopJob() {
|
|
1411
|
-
const deadlineAtMs = getTurnRequestDeadline()?.deadlineAtMs;
|
|
1412
|
-
return deadlineAtMs !== void 0 && Date.now() >= deadlineAtMs - JOB_STOP_BUFFER_MS;
|
|
1413
|
-
}
|
|
1414
|
-
/** Run a snapshot build and send another job if it needs more time. */
|
|
1415
|
-
async function processWorkspaceSnapshotJob(message, options = {}) {
|
|
1416
|
-
const workspace = await getWorkspace(getDb(), message.workspaceId);
|
|
1417
|
-
if (!workspace) {
|
|
1418
|
-
logInfo("workspace.snapshot.job.workspace_missing", { "app.workspace.id": message.workspaceId });
|
|
1419
|
-
await publishFinishedEvent({
|
|
1420
|
-
workspaceId: message.workspaceId,
|
|
1421
|
-
resultId: message.profileHash,
|
|
1422
|
-
status: "failed"
|
|
1423
|
-
});
|
|
1424
|
-
return;
|
|
1425
|
-
}
|
|
1426
|
-
const value = create(SANDBOX_RUNTIME, workspace);
|
|
1427
|
-
if (!value || value.hash !== message.profileHash) {
|
|
1428
|
-
logInfo("workspace.snapshot.job.profile_mismatch", {
|
|
1429
|
-
"app.workspace.id": workspace.id,
|
|
1430
|
-
"app.workspace.snapshot.profile_hash": message.profileHash
|
|
1431
|
-
});
|
|
1432
|
-
return;
|
|
1433
|
-
}
|
|
1434
|
-
const before = await loadSnapshotsForProfile(getDb(), workspace.id, value.hash);
|
|
1435
|
-
if (before.ready) {
|
|
1436
|
-
await publishFinishedEvent({
|
|
1437
|
-
workspaceId: workspace.id,
|
|
1438
|
-
resultId: before.ready.id,
|
|
1439
|
-
status: "ready"
|
|
1440
|
-
});
|
|
1441
|
-
return;
|
|
1442
|
-
}
|
|
1443
|
-
const { applyNetworkPolicy, prepareRepositories } = createSnapshotBuildHelpers();
|
|
1444
|
-
try {
|
|
1445
|
-
await resolveWorkspaceSnapshot({
|
|
1446
|
-
workspace,
|
|
1447
|
-
runtime: SANDBOX_RUNTIME,
|
|
1448
|
-
signal: options.signal,
|
|
1449
|
-
shouldStop: shouldStopJob,
|
|
1450
|
-
applyNetworkPolicy,
|
|
1451
|
-
prepareRepositories,
|
|
1452
|
-
removeCredentialRoute: true
|
|
1453
|
-
});
|
|
1454
|
-
} catch (error) {
|
|
1455
|
-
if (isWorkspaceSnapshotNotReadyError(error)) {
|
|
1456
|
-
await sendNextWorkspaceSnapshotJob(message);
|
|
1457
|
-
return;
|
|
1458
|
-
}
|
|
1459
|
-
const afterFailure = await loadSnapshotsForProfile(getDb(), workspace.id, value.hash);
|
|
1460
|
-
if (afterFailure.build?.status === "failed") {
|
|
1461
|
-
await publishFinishedEvent({
|
|
1462
|
-
workspaceId: workspace.id,
|
|
1463
|
-
resultId: afterFailure.build.id,
|
|
1464
|
-
status: "failed",
|
|
1465
|
-
error: afterFailure.build.error
|
|
1466
|
-
});
|
|
1467
|
-
return;
|
|
1468
|
-
}
|
|
1469
|
-
throw error;
|
|
1470
|
-
}
|
|
1471
|
-
const after = await loadSnapshotsForProfile(getDb(), workspace.id, value.hash);
|
|
1472
|
-
if (after.ready) {
|
|
1473
|
-
await publishFinishedEvent({
|
|
1474
|
-
workspaceId: workspace.id,
|
|
1475
|
-
resultId: after.ready.id,
|
|
1476
|
-
status: "ready"
|
|
1477
|
-
});
|
|
1478
|
-
return;
|
|
1479
|
-
}
|
|
1480
|
-
if (after.build?.status === "failed") {
|
|
1481
|
-
await publishFinishedEvent({
|
|
1482
|
-
workspaceId: workspace.id,
|
|
1483
|
-
resultId: after.build.id,
|
|
1484
|
-
status: "failed",
|
|
1485
|
-
error: after.build.error
|
|
1486
|
-
});
|
|
1487
|
-
return;
|
|
1488
|
-
}
|
|
1489
|
-
await sendNextWorkspaceSnapshotJob(message);
|
|
1490
|
-
}
|
|
1491
|
-
/** Start a snapshot build when no ready snapshot exists. */
|
|
1492
|
-
async function ensureWorkspaceSnapshotBuild(input) {
|
|
1493
|
-
const value = create(SANDBOX_RUNTIME, input.workspace);
|
|
1494
|
-
if (!value) throw new Error(`Workspace ${input.workspace.name} has no snapshot profile`);
|
|
1495
|
-
const current = await loadSnapshotsForProfile(getDb(), input.workspace.id, value.hash);
|
|
1496
|
-
if (current.ready) return "ready";
|
|
1497
|
-
const message = {
|
|
1498
|
-
workspaceId: input.workspace.id,
|
|
1499
|
-
profileHash: value.hash
|
|
1500
|
-
};
|
|
1501
|
-
if (input.sendAgain || current.build) await sendNextWorkspaceSnapshotJob(message);
|
|
1502
|
-
else await sendWorkspaceSnapshotJob(message);
|
|
1503
|
-
return "building";
|
|
1504
|
-
}
|
|
1505
|
-
export { annotateToolResult as A, restoreLineEndings as C, normalizeToLf as D, isMissingPathError as E, listSpaceConfiguration as F, readConversationSpaceConfiguration as I, readConversationSpaceId as L, parseToolInput as M, zodTool as N, positiveInteger as O, zodToolDefinition as P, setSpaceConfiguration as R, prepareTextReplacementArguments as S, validateAndApplyTextEdits as T, editFileToolDefinition as _, prepareWorkspaceSnapshot as a, buildCompactDiff as b, renderToolResultNudge as c, systemTimeToolDefinition as d, createWriteFileTool as f, createEditFileTool as g, readFileToolDefinition as h, requireReadyWorkspaceSnapshot as i, saveObjectAnnotations as j, resolveWorkspacePath as k, PluginToolDeniedError as l, createReadFileTool as m, processWorkspaceSnapshotJob as n, ingestEvent as o, writeFileToolDefinition as p, verifyWorkspaceSnapshotJobMessage as r, createPluginHookRunner as s, ensureWorkspaceSnapshotBuild as t, createSystemTimeTool as u, bashToolDefinition as v, stripBom as w, detectLineEnding as x, createBashTool as y, unsetSpaceConfiguration as z };
|