@segmentstream/agent 0.45.1 → 0.47.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.
Files changed (32) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +25 -3
  3. package/dist/_chunks/{build-metadata-DpMnVUed.mjs → build-metadata-5S6uTvyu.mjs} +1 -1
  4. package/dist/extension/config.d.ts +10 -0
  5. package/dist/extension/config.mjs +11 -0
  6. package/dist/extension/extension.d.ts +5 -0
  7. package/dist/extension/extension.mjs +2 -1
  8. package/dist/extension/hooks/workspace-source.d.ts +6 -0
  9. package/dist/extension/hooks/workspace-source.mjs +10 -0
  10. package/dist/extension/instructions/sandbox.mjs +16 -2
  11. package/dist/extension/lib/actor.mjs +5 -1
  12. package/dist/extension/lib/build-metadata.mjs +1 -1
  13. package/dist/extension/lib/chat-address.d.ts +1 -1
  14. package/dist/extension/lib/chat-address.mjs +1 -1
  15. package/dist/extension/lib/chat-recorder.mjs +11 -0
  16. package/dist/extension/lib/ontology-connection.mjs +7 -3
  17. package/dist/extension/lib/review/hold.mjs +1 -1
  18. package/dist/extension/lib/telegram/adapter.mjs +1 -1
  19. package/dist/extension/lib/telegram/health.mjs +1 -1
  20. package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
  21. package/dist/extension/lib/web/auth.d.ts +60 -0
  22. package/dist/extension/lib/web/auth.mjs +130 -0
  23. package/dist/extension/lib/web/channel.d.ts +15 -0
  24. package/dist/extension/lib/web/channel.mjs +18 -0
  25. package/dist/extension/lib/workspace-source.d.ts +130 -0
  26. package/dist/extension/lib/workspace-source.mjs +451 -0
  27. package/dist/extension/tools/attachments_send.mjs +1 -0
  28. package/dist/extension/tools/workspace_source.d.ts +2 -0
  29. package/dist/extension/tools/workspace_source.mjs +44 -0
  30. package/dist/tools/index.d.ts +1 -0
  31. package/dist/tools/index.mjs +2 -1
  32. package/package.json +7 -4
@@ -0,0 +1,18 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { WEB_PROVIDER, webAuth } from "./auth.mjs";
8
+ import { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";
9
+ import { eveChannel } from "eve/channels/eve";
10
+ function webChannel(options = {}) {
11
+ return eveChannel({ auth: [
12
+ webAuth(options),
13
+ vercelOidc(),
14
+ localDev(),
15
+ placeholderAuth()
16
+ ] });
17
+ }
18
+ export { WEB_PROVIDER, webAuth, webChannel };
@@ -0,0 +1,130 @@
1
+ import { type SessionAuthContext, type StateHandle } from "eve/context";
2
+ import type { HookContext, HookEvent } from "eve/hooks";
3
+ import type { SandboxSession } from "eve/sandbox";
4
+ import { type SandboxRecord } from "./sandbox-session.js";
5
+ /**
6
+ * The workspace's own deployed code in the session's sandbox (`docs/workspace-source-spec.md`,
7
+ * "Sandbox copy"). `segmentstream__workspace_source` reads the ontology's
8
+ * `/api/ontology/agent/source` pages as the turn's member, each a gzip'd ustar archive of one
9
+ * commit's files, checks that every page names the same commit and that no archive names a path
10
+ * outside its root, extracts them beside the copy and swaps it in read-only. Session state records
11
+ * whose copy of which commit the sandbox holds; a `turn.started` guard removes it when another
12
+ * member, or no member, takes a turn, because a group chat's members share the session's sandbox.
13
+ */
14
+ /** Where the copy lives, read-only. */
15
+ export declare const WORKSPACE_SOURCE_DIRECTORY = "/workspace/source";
16
+ /** Where pages are extracted before the copy is swapped in. */
17
+ export declare const WORKSPACE_SOURCE_STAGING_DIRECTORY = "/workspace/source.tmp";
18
+ /** Where the downloaded pages wait for extraction. */
19
+ export declare const WORKSPACE_SOURCE_PAGES_DIRECTORY = "/workspace/.segmentstream/source-pages";
20
+ /** The member, commit and counts of the copy in the sandbox, written once it is complete. */
21
+ export declare const WORKSPACE_SOURCE_MARKER_PATH = "/workspace/.segmentstream/source.json";
22
+ /** The ontology runtime's route; the cursor of a later page goes in `?cursor=`. */
23
+ export declare const WORKSPACE_SOURCE_ROUTE = "/api/ontology/agent/source";
24
+ /**
25
+ * Whose copy of which commit the session's sandbox holds, or is being written, and in which turn.
26
+ * A copy lives for that turn only: the next turn removes it, so the member's permission is checked
27
+ * again, by the ontology, before the code is read in another turn.
28
+ */
29
+ export interface WorkspaceSourceRecord {
30
+ readonly memberId: string;
31
+ readonly commit: string;
32
+ readonly turnId: string;
33
+ }
34
+ export declare const workspaceSourceRecord: StateHandle<WorkspaceSourceRecord | null>;
35
+ /** `/workspace/.segmentstream/source.json`. */
36
+ export interface WorkspaceSourceMarker extends WorkspaceSourceRecord {
37
+ readonly files: number;
38
+ readonly skipped: number;
39
+ /** When the copy was completed, as an ISO timestamp. */
40
+ readonly stagedAt: string;
41
+ }
42
+ /** What the tool answers. */
43
+ export interface WorkspaceSourceCopy {
44
+ readonly path: string;
45
+ readonly commit: string;
46
+ readonly files: number;
47
+ readonly skipped: number;
48
+ readonly reused: boolean;
49
+ }
50
+ /** The copy could not be made; `code` is the ontology's error code, or the SDK's own. */
51
+ export declare class WorkspaceSourceError extends Error {
52
+ readonly name = "WorkspaceSourceError";
53
+ readonly code: string;
54
+ readonly status: number | undefined;
55
+ readonly requestId: string | undefined;
56
+ constructor(input: {
57
+ readonly code: string;
58
+ readonly message: string;
59
+ readonly status?: number;
60
+ readonly requestId?: string;
61
+ }, options?: ErrorOptions);
62
+ }
63
+ /** Who reads the pages, from the turn: the member, and the chat and session it speaks in. */
64
+ export interface WorkspaceSourceReader {
65
+ readonly memberId: string;
66
+ /** Whom the pages are read as: the member, with the proof their channel gives, as on `/mcp`. */
67
+ readonly actAs: Readonly<Record<string, string>>;
68
+ /** The turn the copy is made for; it is removed when the next turn starts. */
69
+ readonly turnId: string;
70
+ /** `<provider>:<chat id>`, as the channels store files; absent outside a channel's chat. */
71
+ readonly chat?: string;
72
+ readonly sessionId: string;
73
+ }
74
+ /** The reader of a session's principal; only a member reads the workspace's code. */
75
+ export declare function workspaceSourceReader(input: {
76
+ readonly principal: SessionAuthContext | null | undefined;
77
+ readonly sessionId: string;
78
+ readonly turnId: string;
79
+ }): WorkspaceSourceReader;
80
+ /**
81
+ * A path the archive may write under its root: relative, without `..` segments or NUL, with
82
+ * segments a file system takes. `.` segments and repeated slashes are tolerated, as tar reads
83
+ * them; other bytes Git allows in a name, such as `Icon\r`, stay as they are.
84
+ */
85
+ export declare function safeArchivePath(path: string): boolean;
86
+ /**
87
+ * Checks a page before it reaches the sandbox: a gzip'd ustar archive whose entries are only
88
+ * regular files and directories, every one at a {@link safeArchivePath}. Links, devices, GNU long
89
+ * names and global pax headers are refused, so extraction writes nothing outside its directory.
90
+ * Answers the regular files' paths.
91
+ */
92
+ export declare function archivePaths(gzipped: Uint8Array): ReadonlyArray<string>;
93
+ /**
94
+ * Extracts the pages into the staging directory, replaces the copy with it and makes it
95
+ * read-only. The marker goes first, so a failure never leaves one naming a copy that is not
96
+ * there. tar refuses absolute and `..` members on its own, besides {@link archivePaths}.
97
+ */
98
+ export declare function installCommand(pages: ReadonlyArray<string>): string;
99
+ /** Removes the copy, anything left of one being written, and the marker. */
100
+ export declare const REMOVE_COMMAND: string;
101
+ /**
102
+ * Copies the commit production runs into `/workspace/source` as the member, or answers the copy
103
+ * the sandbox already holds of it for this member, unless `refresh`. When production moves to
104
+ * another commit while the pages are read, it starts once more.
105
+ */
106
+ export declare function copyWorkspaceSource(input: {
107
+ readonly reader: WorkspaceSourceReader;
108
+ readonly origin: string;
109
+ readonly token: () => Promise<string>;
110
+ readonly fetch?: typeof fetch;
111
+ /** The session's sandbox, after the SDK's gate. */
112
+ readonly sandbox: () => Promise<SandboxSession>;
113
+ readonly refresh?: boolean;
114
+ readonly record?: StateHandle<WorkspaceSourceRecord | null>;
115
+ readonly now?: () => Date;
116
+ }): Promise<WorkspaceSourceCopy>;
117
+ /**
118
+ * The `turn.started` guard. When the session recorded a copy, whoever's turn this is, it removes
119
+ * the copy and the marker from the sandbox and forgets the record: a copy lives for the turn that
120
+ * made it, so a member of a group chat never finds another's copy, and a member whose permission
121
+ * was revoked never keeps reading theirs. It never opens a sandbox without a record, and treats a
122
+ * sandbox the session no longer records as gone with its copy. A failed removal is logged and
123
+ * keeps the record, so the next turn tries again.
124
+ */
125
+ export declare function workspaceSourceGuard(options?: {
126
+ readonly record?: StateHandle<WorkspaceSourceRecord | null>;
127
+ readonly sandbox?: StateHandle<SandboxRecord | null>;
128
+ }): {
129
+ "turn.started"(_event: HookEvent<"turn.started">, context: Pick<HookContext, "session" | "getSandbox">): Promise<void>;
130
+ };
@@ -0,0 +1,451 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname, posix } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { actorHeaders, actorOf } from "./actor.mjs";
8
+ import { CHAT_HEADER, SESSION_HEADER } from "./attachments.mjs";
9
+ import { chatAddressOf } from "./chat-address.mjs";
10
+ import { sandboxRecord } from "./sandbox-session.mjs";
11
+ import { defineState } from "eve/context";
12
+ import { gunzipSync } from "node:zlib";
13
+ const WORKSPACE_SOURCE_DIRECTORY = "/workspace/source";
14
+ const WORKSPACE_SOURCE_STAGING_DIRECTORY = "/workspace/source.tmp";
15
+ const WORKSPACE_SOURCE_PAGES_DIRECTORY = "/workspace/.segmentstream/source-pages";
16
+ const WORKSPACE_SOURCE_MARKER_PATH = "/workspace/.segmentstream/source.json";
17
+ const WORKSPACE_SOURCE_ROUTE = "/api/ontology/agent/source";
18
+ const COMMIT_HEADER = "x-segmentstream-source-commit";
19
+ const FILES_HEADER = "x-segmentstream-source-files";
20
+ const SKIPPED_HEADER = "x-segmentstream-source-skipped";
21
+ const NEXT_HEADER = "x-segmentstream-source-next";
22
+ const COMMIT = /^[0-9a-f]{40}$/;
23
+ const COUNT = /^(?:0|[1-9][0-9]{0,8})$/;
24
+ const PAGE_TIMEOUT_MS = 6e4;
25
+ const MAXIMUM_PAGE_BYTES = 8388608;
26
+ const MAXIMUM_ARCHIVE_BYTES = 33554432;
27
+ const MAXIMUM_PAGES = 200;
28
+ const MAXIMUM_CURSOR_LENGTH = 4096;
29
+ const workspaceSourceRecord = defineState("segmentstream.workspaceSource", () => null);
30
+ var WorkspaceSourceError = class extends Error {
31
+ name = "WorkspaceSourceError";
32
+ code;
33
+ status;
34
+ requestId;
35
+ constructor(input, options) {
36
+ super(`${input.code}: ${input.message}` + (input.requestId === void 0 ? "" : ` request_id ${input.requestId}.`), options);
37
+ this.code = input.code;
38
+ this.status = input.status;
39
+ this.requestId = input.requestId;
40
+ }
41
+ };
42
+ var SourceChanged = class extends Error {};
43
+ function workspaceSourceReader(input) {
44
+ const actor = actorOf(input.principal);
45
+ const chat = chatAddressOf(input.principal);
46
+ if (actor?.kind !== "member") throw new WorkspaceSourceError({
47
+ code: "member_required",
48
+ message: "the workspace's code is copied only for a member."
49
+ });
50
+ return {
51
+ memberId: actor.memberId,
52
+ actAs: actorHeaders({
53
+ actor,
54
+ principal: input.principal
55
+ }),
56
+ turnId: input.turnId,
57
+ ...chat === void 0 ? {} : { chat: `${chat.provider}:${chat.chatId}` },
58
+ sessionId: input.sessionId
59
+ };
60
+ }
61
+ function isRecord(value) {
62
+ return typeof value === "object" && value !== null && !Array.isArray(value);
63
+ }
64
+ function errorCode(body) {
65
+ if (!isRecord(body)) return;
66
+ const code = typeof body.error === "string" ? body.error : body.code;
67
+ if (typeof code === "string") return code;
68
+ return isRecord(body.error) && typeof body.error.code === "string" ? body.error.code : void 0;
69
+ }
70
+ function detailOf(body) {
71
+ const detail = isRecord(body) ? body.detail : void 0;
72
+ return typeof detail === "string" && detail.trim() !== "" ? detail.trim().slice(0, 300) : void 0;
73
+ }
74
+ function requestIdOf(body) {
75
+ const value = isRecord(body) ? body.requestId ?? body.request_id : void 0;
76
+ return typeof value === "string" && value !== "" ? value : void 0;
77
+ }
78
+ function invalidPage(message, options) {
79
+ return new WorkspaceSourceError({
80
+ code: "workspace_source_invalid",
81
+ message
82
+ }, options);
83
+ }
84
+ function unreachable(cause) {
85
+ return new WorkspaceSourceError({
86
+ code: "workspace_source_unreachable",
87
+ message: `${WORKSPACE_SOURCE_ROUTE} did not answer.`
88
+ }, { cause });
89
+ }
90
+ async function refused(response) {
91
+ const body = await response.json().catch(() => void 0);
92
+ const code = errorCode(body);
93
+ const detail = detailOf(body);
94
+ const requestId = requestIdOf(body);
95
+ const status = response.status;
96
+ const failure = (failureCode, message) => new WorkspaceSourceError({
97
+ code: failureCode,
98
+ message: detail === void 0 ? message : `${message} ${detail}`,
99
+ status,
100
+ ...requestId === void 0 ? {} : { requestId }
101
+ });
102
+ if (status === 409 && code === "workspace_source_changed") throw new SourceChanged();
103
+ if (status === 403) throw code === "permission_denied" ? failure(code, "the member may not read this workspace's code (workspace_source:read).") : failure(code ?? "forbidden", "the ontology refused the member (HTTP 403).");
104
+ if ((status === 409 || status === 503) && code === "workspace_source_unavailable") throw failure(code, `the workspace has no deployed source to copy (HTTP ${status}).`);
105
+ if (status === 404 && code === void 0) throw failure("not_found", `the ontology does not serve ${WORKSPACE_SOURCE_ROUTE}.`);
106
+ throw failure(code ?? "workspace_source_failed", `the ontology answered HTTP ${status}.`);
107
+ }
108
+ function header(response, name) {
109
+ const value = response.headers.get(name);
110
+ return value === null ? void 0 : value.trim();
111
+ }
112
+ function count(response, name) {
113
+ const value = header(response, name) ?? "";
114
+ if (!COUNT.test(value)) throw invalidPage(`${name} is not a count.`);
115
+ return Number(value);
116
+ }
117
+ async function boundedBody(response, maximum) {
118
+ if (response.body === null) return new Uint8Array();
119
+ const reader = response.body.getReader();
120
+ const chunks = [];
121
+ let size = 0;
122
+ try {
123
+ for (;;) {
124
+ const next = await reader.read();
125
+ if (next.done) break;
126
+ size += next.value.byteLength;
127
+ if (size > maximum) throw invalidPage(`a page is larger than ${maximum / 1024 / 1024} MiB.`);
128
+ chunks.push(next.value);
129
+ }
130
+ } catch (error) {
131
+ throw error instanceof WorkspaceSourceError ? error : unreachable(error);
132
+ } finally {
133
+ await reader.cancel().catch(() => void 0);
134
+ }
135
+ return new Uint8Array(Buffer.concat(chunks));
136
+ }
137
+ async function requestPage(request, cursor) {
138
+ const { reader } = request;
139
+ const query = cursor === void 0 ? "" : `?cursor=${encodeURIComponent(cursor)}`;
140
+ const authorization = `Bearer ${await request.token()}`;
141
+ let response;
142
+ try {
143
+ response = await request.fetch(`${request.origin}${WORKSPACE_SOURCE_ROUTE}${query}`, {
144
+ headers: {
145
+ authorization,
146
+ ...reader.actAs,
147
+ ...reader.chat === void 0 ? {} : { [CHAT_HEADER]: reader.chat },
148
+ ...reader.sessionId === "" ? {} : { [SESSION_HEADER]: reader.sessionId }
149
+ },
150
+ redirect: "error",
151
+ signal: AbortSignal.timeout(PAGE_TIMEOUT_MS)
152
+ });
153
+ } catch (error) {
154
+ throw unreachable(error);
155
+ }
156
+ if (response.status !== 200) return await refused(response);
157
+ const discard = async () => {
158
+ await response.body?.cancel().catch(() => void 0);
159
+ };
160
+ try {
161
+ const commit = header(response, COMMIT_HEADER) ?? "";
162
+ const next = header(response, NEXT_HEADER);
163
+ if (!COMMIT.test(commit)) throw invalidPage(`${COMMIT_HEADER} is not a commit.`);
164
+ if (next !== void 0 && (next === "" || next.length > MAXIMUM_CURSOR_LENGTH)) throw invalidPage(`${NEXT_HEADER} is not a cursor.`);
165
+ return {
166
+ commit,
167
+ files: count(response, FILES_HEADER),
168
+ skipped: count(response, SKIPPED_HEADER),
169
+ next,
170
+ bytes: () => boundedBody(response, MAXIMUM_PAGE_BYTES),
171
+ discard
172
+ };
173
+ } catch (error) {
174
+ await discard();
175
+ throw error;
176
+ }
177
+ }
178
+ const BLOCK = 512;
179
+ function text(block, start, length) {
180
+ const field = block.subarray(start, start + length);
181
+ const end = field.indexOf(0);
182
+ return Buffer.from(end === -1 ? field : field.subarray(0, end)).toString("utf8");
183
+ }
184
+ function octal(block, start, length) {
185
+ const value = text(block, start, length).trim();
186
+ if (!/^[0-7]{1,12}$/.test(value)) throw invalidPage("an archive header has an invalid number.");
187
+ return Number.parseInt(value, 8);
188
+ }
189
+ const PAX_KEYS = new Set([
190
+ "path",
191
+ "mtime",
192
+ "atime",
193
+ "ctime",
194
+ "uid",
195
+ "gid",
196
+ "uname",
197
+ "gname",
198
+ "charset",
199
+ "hdrcharset",
200
+ "comment"
201
+ ]);
202
+ function paxPath(body) {
203
+ let path;
204
+ let offset = 0;
205
+ while (offset < body.length && body[offset] !== 0) {
206
+ const space = body.indexOf(32, offset);
207
+ const digits = space === -1 ? "" : Buffer.from(body.subarray(offset, space)).toString("ascii");
208
+ const length = /^[1-9][0-9]{0,7}$/.test(digits) ? Number(digits) : NaN;
209
+ if (Number.isNaN(length) || offset + length > body.length || body[offset + length - 1] !== 10) throw invalidPage("an archive has an invalid pax header.");
210
+ const record = Buffer.from(body.subarray(space + 1, offset + length - 1)).toString("utf8");
211
+ const equals = record.indexOf("=");
212
+ const key = equals > 0 ? record.slice(0, equals) : "";
213
+ if (!PAX_KEYS.has(key)) throw invalidPage(`an archive has a pax record that is refused (${key}).`);
214
+ if (key === "path") path = record.slice(equals + 1);
215
+ offset += length;
216
+ }
217
+ return path;
218
+ }
219
+ function safeArchivePath(path) {
220
+ if (path === "" || path.startsWith("/") || path.includes("\0") || path.length > 4096) return false;
221
+ return path.split("/").every((segment) => segment !== ".." && Buffer.byteLength(segment, "utf8") <= 255);
222
+ }
223
+ function archivePaths(gzipped) {
224
+ let archive;
225
+ try {
226
+ archive = gunzipSync(gzipped, { maxOutputLength: MAXIMUM_ARCHIVE_BYTES });
227
+ } catch (error) {
228
+ throw invalidPage("a page is not a gzip archive within its size limit.", { cause: error });
229
+ }
230
+ const files = [];
231
+ let pending;
232
+ let offset = 0;
233
+ for (;;) {
234
+ if (offset + BLOCK > archive.length) throw invalidPage("an archive ends without its end-of-archive blocks.");
235
+ const block = archive.subarray(offset, offset + BLOCK);
236
+ if (block.every((byte) => byte === 0)) {
237
+ if (pending !== void 0) throw invalidPage("an archive ends after a pax header.");
238
+ return files;
239
+ }
240
+ let checksum = 0;
241
+ for (let index = 0; index < BLOCK; index++) checksum += index >= 148 && index < 156 ? 32 : block[index];
242
+ if (checksum !== octal(block, 148, 8) || text(block, 257, 5) !== "ustar") throw invalidPage("an archive header is not a valid ustar header.");
243
+ const type = String.fromCharCode(block[156]);
244
+ const size = octal(block, 124, 12);
245
+ const body = offset + BLOCK;
246
+ const end = body + Math.ceil(size / BLOCK) * BLOCK;
247
+ if (end > archive.length) throw invalidPage("an archive entry is truncated.");
248
+ offset = end;
249
+ if (type === "x") {
250
+ pending = paxPath(archive.subarray(body, body + size)) ?? pending;
251
+ continue;
252
+ }
253
+ const prefix = text(block, 345, 155);
254
+ const name = text(block, 0, 100);
255
+ const path = pending ?? (prefix === "" ? name : `${prefix}/${name}`);
256
+ pending = void 0;
257
+ if (type !== "0" && type !== "\0" && type !== "5") throw invalidPage(`an archive entry is neither a file nor a directory (type ${type}).`);
258
+ if (!safeArchivePath(path)) throw invalidPage("an archive entry names a path outside its root.");
259
+ if (type !== "5") {
260
+ if (posix.normalize(path).replace(/\/+$/, "") === ".") throw invalidPage("an archive file has no name.");
261
+ files.push(path);
262
+ }
263
+ }
264
+ }
265
+ function quoted(value) {
266
+ return `'${value.replaceAll("'", `'\\''`)}'`;
267
+ }
268
+ const SOURCE = quoted(WORKSPACE_SOURCE_DIRECTORY);
269
+ const STAGING = quoted(WORKSPACE_SOURCE_STAGING_DIRECTORY);
270
+ const PAGES = quoted(WORKSPACE_SOURCE_PAGES_DIRECTORY);
271
+ const MARKER = quoted(WORKSPACE_SOURCE_MARKER_PATH);
272
+ const writable = (path) => `if [ -e ${path} ]; then chmod -R u+w ${path}; fi`;
273
+ function installCommand(pages) {
274
+ return [
275
+ "set -eu",
276
+ `rm -f ${MARKER}`,
277
+ writable(STAGING),
278
+ `rm -rf ${STAGING}`,
279
+ `mkdir -p ${STAGING}`,
280
+ ...pages.map((page) => `tar -xzf ${quoted(page)} -C ${STAGING} --no-same-owner --no-same-permissions`),
281
+ writable(SOURCE),
282
+ `rm -rf ${SOURCE}`,
283
+ `mv ${STAGING} ${SOURCE}`,
284
+ `chmod -R a-w ${SOURCE}`,
285
+ `rm -rf ${PAGES}`
286
+ ].join("\n");
287
+ }
288
+ const REMOVE_COMMAND = [
289
+ "set -eu",
290
+ writable(SOURCE),
291
+ writable(STAGING),
292
+ `rm -rf ${SOURCE} ${STAGING} ${PAGES} ${MARKER}`
293
+ ].join("\n");
294
+ function parseMarker(text) {
295
+ let value;
296
+ try {
297
+ value = JSON.parse(text);
298
+ } catch {
299
+ return;
300
+ }
301
+ return isRecord(value) && typeof value.memberId === "string" && typeof value.commit === "string" && typeof value.turnId === "string" && typeof value.files === "number" && typeof value.skipped === "number" && typeof value.stagedAt === "string" ? {
302
+ memberId: value.memberId,
303
+ commit: value.commit,
304
+ turnId: value.turnId,
305
+ files: value.files,
306
+ skipped: value.skipped,
307
+ stagedAt: value.stagedAt
308
+ } : void 0;
309
+ }
310
+ async function installedMarker(sandbox) {
311
+ try {
312
+ const read = await sandbox.run({ command: `test -d ${SOURCE} && cat ${MARKER}` });
313
+ return read.exitCode === 0 ? parseMarker(read.stdout) : void 0;
314
+ } catch (error) {
315
+ console.warn("[segmentstream] workspace source marker could not be read; copying again", { error });
316
+ return;
317
+ }
318
+ }
319
+ async function copyOnce(input) {
320
+ const { memberId, turnId } = input.request.reader;
321
+ const first = await requestPage(input.request, void 0);
322
+ let page = first;
323
+ let sandbox;
324
+ let completed = false;
325
+ try {
326
+ sandbox = await input.sandbox();
327
+ const recorded = input.record.get();
328
+ if (!input.refresh && recorded?.memberId === memberId && recorded.turnId === turnId && recorded.commit === first.commit) {
329
+ const marker = await installedMarker(sandbox);
330
+ if (marker?.memberId === memberId && marker.turnId === turnId && marker.commit === first.commit) {
331
+ completed = true;
332
+ await first.discard();
333
+ return {
334
+ path: WORKSPACE_SOURCE_DIRECTORY,
335
+ commit: first.commit,
336
+ files: marker.files,
337
+ skipped: marker.skipped,
338
+ reused: true
339
+ };
340
+ }
341
+ }
342
+ input.record.update(() => ({
343
+ memberId,
344
+ commit: first.commit,
345
+ turnId
346
+ }));
347
+ const pages = [];
348
+ let files = 0;
349
+ let skipped = 0;
350
+ for (;;) {
351
+ if (page.commit !== first.commit) throw new WorkspaceSourceError({
352
+ code: "workspace_source_inconsistent",
353
+ message: `pages named commits ${first.commit} and ${page.commit}; nothing was replaced.`
354
+ });
355
+ const bytes = await page.bytes();
356
+ const path = `${WORKSPACE_SOURCE_PAGES_DIRECTORY}/${String(pages.length).padStart(4, "0")}.tar.gz`;
357
+ archivePaths(bytes);
358
+ await sandbox.writeBinaryFile({
359
+ path,
360
+ content: bytes
361
+ });
362
+ pages.push(path);
363
+ files += page.files;
364
+ skipped += page.skipped;
365
+ if (page.next === void 0) break;
366
+ if (pages.length >= MAXIMUM_PAGES) throw new WorkspaceSourceError({
367
+ code: "workspace_source_too_large",
368
+ message: `the source has more than ${MAXIMUM_PAGES} pages.`
369
+ });
370
+ page = await requestPage(input.request, page.next);
371
+ }
372
+ const installed = await sandbox.run({ command: installCommand(pages) });
373
+ if (installed.exitCode !== 0) throw new WorkspaceSourceError({
374
+ code: "workspace_source_install_failed",
375
+ message: `extraction exited ${installed.exitCode}: ${installed.stderr.slice(0, 1e3)}`
376
+ });
377
+ const marker = {
378
+ memberId,
379
+ commit: first.commit,
380
+ turnId,
381
+ files,
382
+ skipped,
383
+ stagedAt: input.now().toISOString()
384
+ };
385
+ await sandbox.writeTextFile({
386
+ path: WORKSPACE_SOURCE_MARKER_PATH,
387
+ content: `${JSON.stringify(marker)}\n`
388
+ });
389
+ completed = true;
390
+ return {
391
+ path: WORKSPACE_SOURCE_DIRECTORY,
392
+ commit: first.commit,
393
+ files,
394
+ skipped,
395
+ reused: false
396
+ };
397
+ } finally {
398
+ if (!completed) {
399
+ await page.discard();
400
+ if (sandbox !== void 0) await sandbox.run({ command: `rm -rf ${STAGING} ${PAGES}` }).then(void 0, (error) => {
401
+ console.warn("[segmentstream] workspace source cleanup failed", { error });
402
+ });
403
+ }
404
+ }
405
+ }
406
+ async function copyWorkspaceSource(input) {
407
+ const pass = {
408
+ request: {
409
+ reader: input.reader,
410
+ origin: input.origin,
411
+ token: input.token,
412
+ fetch: input.fetch ?? fetch
413
+ },
414
+ sandbox: input.sandbox,
415
+ refresh: input.refresh === true,
416
+ record: input.record ?? workspaceSourceRecord,
417
+ now: input.now ?? (() => new Date())
418
+ };
419
+ for (let attempt = 0;; attempt++) try {
420
+ return await copyOnce(pass);
421
+ } catch (error) {
422
+ if (!(error instanceof SourceChanged)) throw error;
423
+ if (attempt > 0) throw new WorkspaceSourceError({
424
+ code: "workspace_source_changed",
425
+ message: "production moved to another commit twice while the pages were read.",
426
+ status: 409
427
+ }, { cause: error });
428
+ }
429
+ }
430
+ function workspaceSourceGuard(options = {}) {
431
+ return { async "turn.started"(_event, context) {
432
+ const record = options.record ?? workspaceSourceRecord;
433
+ if (record.get() === null) return;
434
+ if ((options.sandbox ?? sandboxRecord).get() === null) {
435
+ record.update(() => null);
436
+ return;
437
+ }
438
+ try {
439
+ const removed = await (await context.getSandbox()).run({ command: REMOVE_COMMAND });
440
+ if (removed.exitCode !== 0) throw new Error(`Removal exited ${removed.exitCode}: ${removed.stderr.slice(0, 1e3)}`);
441
+ record.update(() => null);
442
+ } catch (error) {
443
+ console.error("[segmentstream] workspace source removal failed", {
444
+ sessionId: context.session.id,
445
+ turnId: context.session.turn.id,
446
+ error
447
+ });
448
+ }
449
+ } };
450
+ }
451
+ export { REMOVE_COMMAND, WORKSPACE_SOURCE_DIRECTORY, WORKSPACE_SOURCE_MARKER_PATH, WORKSPACE_SOURCE_PAGES_DIRECTORY, WORKSPACE_SOURCE_ROUTE, WORKSPACE_SOURCE_STAGING_DIRECTORY, WorkspaceSourceError, archivePaths, copyWorkspaceSource, installCommand, safeArchivePath, workspaceSourceGuard, workspaceSourceReader, workspaceSourceRecord };
@@ -53,6 +53,7 @@ const tool = defineTool({
53
53
  label: { start: () => "Send stored attachments" },
54
54
  async execute(input, ctx) {
55
55
  const principal = ctx.session.auth.current;
56
+ if (chatAddressOf(principal)?.provider === "web") throw new Error("Stored attachments cannot be sent in a web chat; link to them instead.");
56
57
  const options = {
57
58
  input: sendAttachmentsInput(input),
58
59
  principal,
@@ -0,0 +1,2 @@
1
+ declare const _default: import("eve").DynamicSentinel<import("eve/tools").DynamicToolResult, import("eve").DynamicContext>;
2
+ export default _default;
@@ -0,0 +1,44 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import segmentstream from "../extension.mjs";
8
+ import { actorOf } from "../lib/actor.mjs";
9
+ import { appOrigin } from "../lib/environment.mjs";
10
+ import { runtimeToken } from "../lib/runtime-token.mjs";
11
+ import { sessionSandbox } from "../lib/sandbox-session.mjs";
12
+ import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
13
+ import { copyWorkspaceSource, workspaceSourceReader } from "../lib/workspace-source.mjs";
14
+ import { defineDynamic, defineTool } from "eve/tools";
15
+ const tool = defineTool({
16
+ description: "Copy this workspace's deployed code (the commit of main that production runs) into /workspace/source, read-only, as the current member, to find out what the workspace can and cannot do or why something fails. The code is for your own understanding, not to show the member. Call it before reading the workspace's own code, then search it with rg and read its files there. Answers the path, the commit and the counts of files copied and skipped. The copy lasts for this turn; in this turn a copy of the same commit is reused unless refresh is true.",
17
+ inputSchema: {
18
+ type: "object",
19
+ properties: { refresh: {
20
+ type: "boolean",
21
+ description: "Copy again even when the sandbox holds this commit."
22
+ } },
23
+ additionalProperties: false
24
+ },
25
+ label: { start: () => "Copy the workspace's code into the sandbox" },
26
+ async execute(input, ctx) {
27
+ const refresh = input.refresh;
28
+ if (refresh !== void 0 && typeof refresh !== "boolean") throw new TypeError("refresh must be true or false.");
29
+ const copy = await copyWorkspaceSource({
30
+ reader: workspaceSourceReader({
31
+ principal: ctx.session.auth.current,
32
+ sessionId: ctx.session.id,
33
+ turnId: ctx.session.turn.id
34
+ }),
35
+ origin: appOrigin(),
36
+ token: runtimeToken,
37
+ sandbox: () => sessionSandbox(ctx),
38
+ refresh: refresh === true
39
+ });
40
+ return workflowToolResult(copy, ctx);
41
+ }
42
+ });
43
+ var workspace_source_default = defineDynamic((context) => segmentstream.config.sandbox && segmentstream.config.workspaceSource === true && actorOf(context.session.auth.current)?.kind === "member" ? tool : null);
44
+ export { workspace_source_default as default };
@@ -11,3 +11,4 @@ export { default as no_reply } from "../extension/tools/no_reply.js";
11
11
  export { default as ontology_call_file } from "../extension/tools/ontology_call_file.js";
12
12
  export { default as questions_ask } from "../extension/tools/questions_ask.js";
13
13
  export { default as sandbox } from "../extension/tools/sandbox.js";
14
+ export { default as workspace_source } from "../extension/tools/workspace_source.js";
@@ -15,4 +15,5 @@ import no_reply_default from "../extension/tools/no_reply.mjs";
15
15
  import ontology_call_file_default from "../extension/tools/ontology_call_file.mjs";
16
16
  import questions_ask_default from "../extension/tools/questions_ask.mjs";
17
17
  import sandbox_default from "../extension/tools/sandbox.mjs";
18
- export { attachments_discard_default as attachments_discard, attachments_list_default as attachments_list, attachments_promote_default as attachments_promote, attachments_read_default as attachments_read, attachments_send_default as attachments_send, attachments_stage_default as attachments_stage, attachments_table_default as attachments_table, no_reply_default as no_reply, ontology_call_file_default as ontology_call_file, questions_ask_default as questions_ask, sandbox_default as sandbox };
18
+ import workspace_source_default from "../extension/tools/workspace_source.mjs";
19
+ export { attachments_discard_default as attachments_discard, attachments_list_default as attachments_list, attachments_promote_default as attachments_promote, attachments_read_default as attachments_read, attachments_send_default as attachments_send, attachments_stage_default as attachments_stage, attachments_table_default as attachments_table, no_reply_default as no_reply, ontology_call_file_default as ontology_call_file, questions_ask_default as questions_ask, sandbox_default as sandbox, workspace_source_default as workspace_source };