@segmentstream/agent 0.45.1 → 0.48.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/CHANGELOG.md +56 -0
- package/README.md +36 -15
- package/dist/_chunks/{build-metadata-DpMnVUed.mjs → build-metadata-DjhDPTy-.mjs} +1 -1
- package/dist/extension/config.d.ts +10 -0
- package/dist/extension/config.mjs +11 -0
- package/dist/extension/extension.d.ts +5 -0
- package/dist/extension/extension.mjs +2 -1
- package/dist/extension/hooks/workspace-source.d.ts +6 -0
- package/dist/extension/hooks/workspace-source.mjs +10 -0
- package/dist/extension/instructions/sandbox.mjs +16 -2
- package/dist/extension/lib/actor.mjs +5 -1
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/chat-address.d.ts +1 -1
- package/dist/extension/lib/chat-address.mjs +1 -1
- package/dist/extension/lib/chat-recorder.mjs +11 -0
- package/dist/extension/lib/ontology-connection.mjs +7 -3
- package/dist/extension/lib/review/hold.mjs +1 -1
- package/dist/extension/lib/telegram/adapter.mjs +1 -1
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/dist/extension/lib/web/auth.d.ts +83 -0
- package/dist/extension/lib/web/auth.mjs +174 -0
- package/dist/extension/lib/web/channel.d.ts +15 -0
- package/dist/extension/lib/web/channel.mjs +18 -0
- package/dist/extension/lib/workspace-source.d.ts +130 -0
- package/dist/extension/lib/workspace-source.mjs +451 -0
- package/dist/extension/tools/attachments_send.mjs +1 -0
- package/dist/extension/tools/workspace_source.d.ts +2 -0
- package/dist/extension/tools/workspace_source.mjs +44 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.mjs +2 -1
- package/package.json +7 -4
|
@@ -0,0 +1,174 @@
|
|
|
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 { withButtonDecision } from "../confirmation-buttons.mjs";
|
|
8
|
+
import { withChatAddress } from "../chat-address.mjs";
|
|
9
|
+
import { appOrigin } from "../environment.mjs";
|
|
10
|
+
import { runtimeToken } from "../runtime-token.mjs";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { ForbiddenError, UnauthenticatedError } from "eve/channels/auth";
|
|
13
|
+
const WEB_AUTHENTICATOR = "segmentstream-web";
|
|
14
|
+
const WEB_PROVIDER = "web";
|
|
15
|
+
const AGENT_GRANT_HEADER = "X-SegmentStream-Agent-Grant";
|
|
16
|
+
const WEB_GRANT_ATTRIBUTE = "webGrant";
|
|
17
|
+
const ACCESS_TOKEN_PREFIX = "sso_";
|
|
18
|
+
const INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
|
|
19
|
+
const INTROSPECTION_TIMEOUT_MS = 5e3;
|
|
20
|
+
const ANSWER_TTL_MS = 6e4;
|
|
21
|
+
const ANSWER_LIMIT = 1e3;
|
|
22
|
+
const TURN_LIMITED_CODE = "rate_limited";
|
|
23
|
+
var TurnLimitedError = class extends ForbiddenError {
|
|
24
|
+
retryAfterSeconds;
|
|
25
|
+
response;
|
|
26
|
+
constructor(retryAfterSeconds) {
|
|
27
|
+
super({
|
|
28
|
+
code: TURN_LIMITED_CODE,
|
|
29
|
+
message: TURN_LIMITED_CODE
|
|
30
|
+
});
|
|
31
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
32
|
+
this.name = "TurnLimitedError";
|
|
33
|
+
this.response = Response.json({
|
|
34
|
+
code: TURN_LIMITED_CODE,
|
|
35
|
+
ok: false,
|
|
36
|
+
retry_after_seconds: retryAfterSeconds
|
|
37
|
+
}, {
|
|
38
|
+
status: 429,
|
|
39
|
+
headers: {
|
|
40
|
+
"cache-control": "no-store",
|
|
41
|
+
"retry-after": String(retryAfterSeconds)
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
function strings(value) {
|
|
47
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
|
|
48
|
+
}
|
|
49
|
+
function webMemberOf(body) {
|
|
50
|
+
if (typeof body !== "object" || body === null) return;
|
|
51
|
+
const answer = body;
|
|
52
|
+
const roles = strings(answer.roles);
|
|
53
|
+
if (answer.active !== true || typeof answer.member_id !== "string" || typeof answer.grant_id !== "string" || answer.chat !== `member:${answer.member_id}` || roles === void 0) return;
|
|
54
|
+
const limited = answer.limited;
|
|
55
|
+
return {
|
|
56
|
+
memberId: answer.member_id,
|
|
57
|
+
grant: answer.grant_id,
|
|
58
|
+
chat: answer.chat,
|
|
59
|
+
roles,
|
|
60
|
+
...typeof answer.name === "string" && answer.name !== "" ? { name: answer.name } : {},
|
|
61
|
+
...typeof limited === "object" && limited !== null && typeof limited.retry_after_seconds === "number" ? { limited: {
|
|
62
|
+
scope: typeof limited.scope === "string" ? limited.scope : "",
|
|
63
|
+
retryAfterSeconds: limited.retry_after_seconds
|
|
64
|
+
} } : {}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function ontologyIntrospection(options = {}) {
|
|
68
|
+
return async (token, origin, turn) => {
|
|
69
|
+
const ask = async (body) => (options.fetch ?? fetch)(`${appOrigin(options.environment ?? process.env)}${INTROSPECTION_PATH}`, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: {
|
|
72
|
+
authorization: `Bearer ${await (options.token ?? runtimeToken)()}`,
|
|
73
|
+
"content-type": "application/json"
|
|
74
|
+
},
|
|
75
|
+
body: JSON.stringify(body),
|
|
76
|
+
signal: AbortSignal.timeout(INTROSPECTION_TIMEOUT_MS)
|
|
77
|
+
});
|
|
78
|
+
let response = await ask({
|
|
79
|
+
token,
|
|
80
|
+
origin,
|
|
81
|
+
...turn === true ? { turn: true } : {}
|
|
82
|
+
});
|
|
83
|
+
if (turn === true && response.status === 400) response = await ask({
|
|
84
|
+
token,
|
|
85
|
+
origin
|
|
86
|
+
});
|
|
87
|
+
if (!response.ok) throw new Error(`The ontology could not say whom an agent token stands for (${response.status}).`);
|
|
88
|
+
return webMemberOf(await response.json());
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function webPrincipal(member) {
|
|
92
|
+
const chat = {
|
|
93
|
+
provider: "web",
|
|
94
|
+
chatId: member.chat,
|
|
95
|
+
threadId: "",
|
|
96
|
+
kind: "private",
|
|
97
|
+
peer: member.memberId
|
|
98
|
+
};
|
|
99
|
+
const attributes = {
|
|
100
|
+
memberId: member.memberId,
|
|
101
|
+
identityProvider: "web",
|
|
102
|
+
roles: member.roles,
|
|
103
|
+
[WEB_GRANT_ATTRIBUTE]: member.grant
|
|
104
|
+
};
|
|
105
|
+
if (member.name !== void 0) attributes.memberName = member.name;
|
|
106
|
+
return withChatAddress({
|
|
107
|
+
authenticator: WEB_AUTHENTICATOR,
|
|
108
|
+
principalId: `web:${member.memberId}`,
|
|
109
|
+
principalType: "user",
|
|
110
|
+
subject: member.memberId,
|
|
111
|
+
attributes
|
|
112
|
+
}, chat);
|
|
113
|
+
}
|
|
114
|
+
function webGrantOf(principal) {
|
|
115
|
+
const grant = principal?.attributes[WEB_GRANT_ATTRIBUTE];
|
|
116
|
+
return principal?.authenticator === "segmentstream-web" && typeof grant === "string" && grant !== "" ? grant : void 0;
|
|
117
|
+
}
|
|
118
|
+
function bearerOf(request) {
|
|
119
|
+
const header = request.headers.get("authorization") ?? "";
|
|
120
|
+
return /^Bearer\s+(.+)$/iu.exec(header.trim())?.[1];
|
|
121
|
+
}
|
|
122
|
+
async function bodyOf(request) {
|
|
123
|
+
if (request.method !== "POST") return;
|
|
124
|
+
try {
|
|
125
|
+
const body = await request.clone().json();
|
|
126
|
+
return typeof body === "object" && body !== null ? body : void 0;
|
|
127
|
+
} catch {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function answersOf(body) {
|
|
132
|
+
const answers = body?.answers;
|
|
133
|
+
return Array.isArray(answers) ? answers.filter((answer) => typeof answer === "object" && answer !== null && typeof answer.interactionId === "string") : [];
|
|
134
|
+
}
|
|
135
|
+
function startsTurn(body) {
|
|
136
|
+
return body?.message !== void 0 && body.message !== null;
|
|
137
|
+
}
|
|
138
|
+
function answerCache(introspect) {
|
|
139
|
+
const answers = new Map();
|
|
140
|
+
return async (token, origin, turn) => {
|
|
141
|
+
if (turn === true) return introspect(token, origin, true);
|
|
142
|
+
const key = createHash("sha256").update(`${origin} ${token}`).digest("hex");
|
|
143
|
+
const now = Date.now();
|
|
144
|
+
const kept = answers.get(key);
|
|
145
|
+
if (kept !== void 0 && kept.until > now) return kept.member;
|
|
146
|
+
answers.delete(key);
|
|
147
|
+
const member = await introspect(token, origin, false);
|
|
148
|
+
if (member !== void 0) {
|
|
149
|
+
if (answers.size >= ANSWER_LIMIT) answers.delete(answers.keys().next().value);
|
|
150
|
+
answers.set(key, {
|
|
151
|
+
member,
|
|
152
|
+
until: now + ANSWER_TTL_MS
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return member;
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function webAuth(options = {}) {
|
|
159
|
+
let introspect;
|
|
160
|
+
return async (request) => {
|
|
161
|
+
const token = bearerOf(request);
|
|
162
|
+
if (token === void 0 || !token.startsWith("sso_")) return null;
|
|
163
|
+
introspect ??= answerCache(options.introspect ?? ontologyIntrospection());
|
|
164
|
+
const body = await bodyOf(request);
|
|
165
|
+
const member = await introspect(token, new URL(request.url).origin, startsTurn(body));
|
|
166
|
+
if (member === void 0) throw new UnauthenticatedError({
|
|
167
|
+
code: "agent_token_invalid",
|
|
168
|
+
message: "The agent token is invalid or expired."
|
|
169
|
+
});
|
|
170
|
+
if (member.limited !== void 0) throw new TurnLimitedError(member.limited.retryAfterSeconds);
|
|
171
|
+
return withButtonDecision(webPrincipal(member), answersOf(body));
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
export { ACCESS_TOKEN_PREFIX, AGENT_GRANT_HEADER, INTROSPECTION_PATH, TURN_LIMITED_CODE, TurnLimitedError, WEB_AUTHENTICATOR, WEB_GRANT_ATTRIBUTE, WEB_PROVIDER, ontologyIntrospection, webAuth, webGrantOf, webMemberOf, webPrincipal };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type WebAuthOptions } from "./auth.js";
|
|
2
|
+
/**
|
|
3
|
+
* The agent's own HTTP channel, which browsers talk to: a member who shows an agent token from the
|
|
4
|
+
* ontology talks to the agent as themselves, in their own chat; every other request keeps the
|
|
5
|
+
* runtime's defaults (this deployment's own functions, local development). The runtime reads this
|
|
6
|
+
* channel only from the agent's `agent/channels/eve.ts`, whose name it fixes:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { webChannel } from "@segmentstream/agent/web";
|
|
10
|
+
*
|
|
11
|
+
* export default webChannel();
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export declare function webChannel(options?: WebAuthOptions): import("eve/channels/eve").EveChannel;
|
|
15
|
+
export { WEB_PROVIDER, webAuth, type WebAuthOptions, type WebIntrospection } from "./auth.js";
|
|
@@ -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
|
+
};
|