@ai-ecoverse/slicc-agent 7.25.1 → 7.27.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/README.md +9 -6
- package/dist/approvals/index.js +5 -4
- package/dist/approvals/index.js.map +2 -2
- package/dist/approvals/people.js +5 -0
- package/dist/approvals/people.js.map +7 -0
- package/dist/approvals/record.js +5 -2
- package/dist/approvals/record.js.map +2 -2
- package/dist/approvals/sudo-client.js +11 -4
- package/dist/approvals/sudo-client.js.map +2 -2
- package/dist/approvals/sudo.js +13 -5
- package/dist/approvals/sudo.js.map +2 -2
- package/dist/attachments.js +92 -43
- package/dist/attachments.js.map +2 -2
- package/dist/index.js.map +2 -2
- package/dist/main.js +27 -7
- package/dist/main.js.map +2 -2
- package/dist/page.js.map +2 -2
- package/dist/spectrum/agent-port.js +36 -7
- package/dist/spectrum/agent-port.js.map +2 -2
- package/dist/spectrum/outgoing.js +85 -24
- package/dist/spectrum/outgoing.js.map +2 -2
- package/dist/staging.js +42 -0
- package/dist/staging.js.map +7 -0
- package/dist/types/approvals/people.d.ts +2 -0
- package/dist/types/approvals/record.d.ts +5 -3
- package/dist/types/approvals/sudo-client.d.ts +1 -1
- package/dist/types/approvals/sudo.d.ts +9 -1
- package/dist/types/attachments.d.ts +13 -3
- package/dist/types/index.d.ts +1 -1
- package/dist/types/main.d.ts +1 -0
- package/dist/types/page.d.ts +1 -1
- package/dist/types/spectrum/agent-port.d.ts +2 -0
- package/dist/types/spectrum/outgoing.d.ts +12 -3
- package/dist/types/staging.d.ts +13 -0
- package/dist/types/uploads.d.ts +2 -0
- package/dist/uploads.js +3 -1
- package/dist/uploads.js.map +2 -2
- package/package.json +4 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/sudo.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context, ReplicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { AgentsState } from '../agents.ts';\nimport type { AgentCapture } from '../guests/capture.ts';\nimport type { Licks } from '../licks/licks.ts';\nimport { sprinklesOf } from '../sprinkles/cgi.ts';\nimport type { Approvals } from './index.ts';\nimport {\n type Approval,\n type ApprovalRequester,\n cleanReason,\n REASONS,\n type SudoDetail,\n type SudoStdin,\n} from './record.ts';\n\nexport type SudoAnswer = 'once' | 'always' | 'deny';\n\nexport type SudoDenial = { answer: 'deny'; message: string };\n\nexport type SudoReply = SudoAnswer | SudoDenial;\n\nexport interface SudoRequest {\n id: string;\n kind: 'sudo';\n user: string;\n uid?: number;\n target?: string;\n argv: string[];\n path?: string;\n cwd?: string;\n pid?: number;\n tag?: string;\n tags?: string[];\n tty?: string;\n createdAt?: number;\n expiresAt: number;\n always?: boolean;\n stdin?: SudoStdin;\n rootOnly?: Record<string, boolean>;\n}\n\nexport type SudoAsked = { id: string; error: null } | { id: null; error: string };\n\nexport interface AgentSudo extends AgentCapture {\n readonly approvals: ReplicatedState<Approval[]>;\n request(request: SudoRequest, where: string | null, context: Context): Promise<SudoAsked>;\n withdraw(id: string, reason: string | null, context: Context): Promise<void>;\n}\n\nconst SAFE = /^[\\w@%+=:,./-]+$/;\n\nexport const shellWord = (word: string): string =>\n SAFE.test(word) ? word : `'${word.replaceAll(\"'\", `'\\\\''`)}'`;\n\nconst text = (value: unknown): value is string => typeof value === 'string';\n\nexport function sudoRequest(value: unknown): SudoRequest | null {\n const request = value as Partial<SudoRequest> | null;\n if (typeof request !== 'object' || request === null || request.kind !== 'sudo') return null;\n const { argv, user, expiresAt } = request;\n if (!Array.isArray(argv) || !argv.
|
|
5
|
-
"mappings": "AACA,SAAS,0BAA0B;AAInC,SAAS,mBAAmB;AAE5B;AAAA,EAGE;AAAA,EACA;AAAA,OAGK;
|
|
4
|
+
"sourcesContent": ["import type { Context, ReplicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { AgentsState } from '../agents.ts';\nimport type { AgentCapture } from '../guests/capture.ts';\nimport type { Licks } from '../licks/licks.ts';\nimport { sprinklesOf } from '../sprinkles/cgi.ts';\nimport type { Approvals } from './index.ts';\nimport {\n type Approval,\n type ApprovalRequester,\n cleanReason,\n REASONS,\n type SudoDetail,\n type SudoStdin,\n} from './record.ts';\n\nexport type SudoAnswer = 'once' | 'always' | 'deny';\n\nexport type SudoDenial = { answer: 'deny'; message: string };\n\nexport type SudoTimestamp = { answer: 'once' | 'always'; timestamp: true };\n\nexport type SudoReply = SudoAnswer | SudoDenial | SudoTimestamp;\n\nexport interface SudoRequest {\n id: string;\n kind: 'sudo';\n user: string;\n uid?: number;\n target?: string;\n argv: string[];\n path?: string;\n cwd?: string;\n pid?: number;\n tag?: string;\n tags?: string[];\n tty?: string;\n createdAt?: number;\n expiresAt: number;\n always?: boolean;\n stdin?: SudoStdin;\n rootOnly?: Record<string, boolean>;\n timestamp?: boolean;\n validate?: boolean;\n}\n\nexport type SudoAsked = { id: string; error: null } | { id: null; error: string };\n\nexport interface AgentSudo extends AgentCapture {\n readonly approvals: ReplicatedState<Approval[]>;\n request(request: SudoRequest, where: string | null, context: Context): Promise<SudoAsked>;\n withdraw(id: string, reason: string | null, context: Context): Promise<void>;\n}\n\nconst SAFE = /^[\\w@%+=:,./-]+$/;\n\nexport const shellWord = (word: string): string =>\n SAFE.test(word) ? word : `'${word.replaceAll(\"'\", `'\\\\''`)}'`;\n\nconst text = (value: unknown): value is string => typeof value === 'string';\n\nexport function sudoRequest(value: unknown): SudoRequest | null {\n const request = value as Partial<SudoRequest> | null;\n if (typeof request !== 'object' || request === null || request.kind !== 'sudo') return null;\n const { argv, user, expiresAt } = request;\n if (!Array.isArray(argv) || !argv.every(text)) return null;\n if (!argv.length && request.validate !== true) return null;\n if (!text(user) || typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return null;\n return request as SudoRequest;\n}\n\nfunction tagOf(tag: unknown): { kind?: unknown; agentId?: unknown; where?: unknown } | null {\n if (!text(tag)) return null;\n try {\n const parsed = JSON.parse(tag);\n return typeof parsed === 'object' && parsed !== null ? parsed : null;\n } catch {\n return null;\n }\n}\n\nconst TERMINAL = 'terminal:';\nconst FOLLOWER = 'follower:';\n\nfunction shownWhere(where: string, given: string | undefined): string {\n if (given) return given;\n if (where.startsWith(TERMINAL)) return 'a terminal';\n if (where.startsWith(FOLLOWER)) return 'a linked device';\n return where;\n}\n\nexport function sudoRequester(\n request: SudoRequest,\n agents: Readonly<AgentsState> | undefined,\n where?: string | null\n): { requester: ApprovalRequester; agentId: string } {\n const tag = tagOf(request.tag);\n const name = request.user;\n const sprinkle = sprinklesOf(Array.isArray(request.tags) ? request.tags.filter(text) : [])[0];\n if (sprinkle)\n return { requester: { kind: 'user', name, where: `the ${sprinkle} sprinkle` }, agentId: '' };\n if (tag?.kind === 'agent' && text(tag.agentId)) {\n const id = tag.agentId.startsWith('cone:') ? tag.agentId.slice('cone:'.length) : tag.agentId;\n const known = agents?.cones[id]?.name ?? agents?.scoops[id]?.name ?? name;\n return { requester: { kind: 'agent', name: known, agentId: id }, agentId: id };\n }\n if (tag?.kind === 'user' && text(tag.where)) {\n const given = cleanReason(where);\n const device = tag.where.startsWith(FOLLOWER) ? tag.where.slice(FOLLOWER.length) : '';\n return {\n requester: {\n kind: 'user',\n name,\n where: shownWhere(tag.where, given),\n ...(device ? { device } : {}),\n },\n agentId: '',\n };\n }\n return { requester: { kind: 'user', name }, agentId: '' };\n}\n\nconst STDIN: readonly unknown[] = ['tty', 'none', 'pipe', 'file'];\n\nfunction rootOnlyOf(value: unknown): Record<string, boolean> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const kept = Object.entries(value).filter(\n (entry): entry is [string, boolean] => typeof entry[1] === 'boolean'\n );\n return Object.fromEntries(kept);\n}\n\nfunction kernelFacts(request: SudoRequest): Partial<SudoDetail> {\n const rootOnly = rootOnlyOf(request.rootOnly);\n return {\n ...(STDIN.includes(request.stdin) ? { stdin: request.stdin } : {}),\n ...(rootOnly ? { rootOnly } : {}),\n ...(typeof request.always === 'boolean' ? { writable: request.always } : {}),\n };\n}\n\nexport const validating = (request: Pick<SudoRequest, 'validate'>): boolean =>\n request.validate === true;\n\nexport const timestampFor = (user: string): string =>\n `start a sudo timestamp for ${user} (no command)`;\n\nexport function sudoDetail(request: SudoRequest): SudoDetail {\n if (validating(request))\n return { command: timestampFor(request.user), validate: true, writable: false };\n const command = [request.path || request.argv[0], ...request.argv.slice(1)]\n .map((word) => shellWord(String(word)))\n .join(' ');\n return {\n command,\n ...(text(request.target) ? { target: request.target } : {}),\n ...(text(request.cwd) ? { cwd: request.cwd } : {}),\n ...(request.always === true ? { alwaysScope: 'cwd' as const } : {}),\n ...kernelFacts(request),\n };\n}\n\nfunction scoopLick(\n id: string,\n agentId: string,\n detail: SudoDetail,\n agents: Readonly<AgentsState> | undefined\n) {\n const scoop = agents?.scoops[agentId];\n if (!scoop) return undefined;\n const { command, target, cwd, validate } = detail;\n const as = target ? ` as ${target}` : '';\n const at = cwd ? ` in ${cwd}` : '';\n const asked = validate ? 'to start a sudo timestamp' : `to run ${command}${as}${at}`;\n return {\n channel: 'sudo-request' as const,\n source: id,\n title: `${scoop.name} waits for sudo`,\n text: `[scoop ${scoop.name} waits for a person to approve sudo]`,\n body: `${scoop.name} asked ${asked}. A person answers it in the approvals dialog; you can't approve it. It ends when someone answers or it times out.`,\n target: `cone:${scoop.cone}` as const,\n };\n}\n\nexport interface SudoAttach {\n approvals: Approvals;\n capture: AgentCapture;\n agents?: () => Readonly<AgentsState> | undefined;\n licks?: Pick<Licks, 'deliver'>;\n}\n\ntype SudoLick = NonNullable<ReturnType<typeof scoopLick>>;\n\nexport function createSudo(options: SudoAttach): AgentSudo & { close(): void } {\n const { approvals } = options;\n const agents = () => options.agents?.();\n const waiting = new Map<string, SudoLick>();\n const send = (lick: SudoLick) =>\n void options.licks?.deliver(lick, BACKGROUND_CONTEXT).catch(() => undefined);\n const watch = (items: readonly Approval[]) => {\n for (const [id, lick] of waiting) {\n const item = items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.tier !== 'user') continue;\n waiting.delete(id);\n if (item?.state === 'pending') send(lick);\n }\n };\n const off = approvals.state.subscribe((items) => watch(items));\n return {\n approvals: approvals.state,\n capture: (request, where, context) => options.capture.capture(request, where, context),\n async request(value, where, context) {\n const request = sudoRequest(value);\n if (!request) return { id: null, error: 'This is not a sudo request.' };\n const { requester, agentId } = sudoRequester(request, agents(), where);\n const detail = sudoDetail(request);\n const item = await approvals.request(\n {\n kind: 'sudo',\n agentId,\n requester,\n tier: 'user',\n always: request.always !== false && !validating(request),\n expiresAt: request.expiresAt,\n detail,\n },\n context\n );\n const lick = scoopLick(item.id, agentId, detail, agents());\n if (lick) {\n waiting.set(item.id, lick);\n watch(approvals.state.value as Approval[]);\n }\n return { id: item.id, error: null };\n },\n async withdraw(id, reason, context) {\n await approvals.withdraw(id, reason, context);\n },\n close() {\n off();\n waiting.clear();\n },\n };\n}\n\nexport function ownedSudo(sudo: AgentSudo): AgentSudo & { release(): void } {\n const mine = new Set<string>();\n const forget = () => {\n const open = new Set(\n (sudo.approvals.value as Approval[])\n .filter((item) => item.state === 'pending')\n .map(({ id }) => id)\n );\n for (const id of mine) if (!open.has(id)) mine.delete(id);\n };\n return {\n approvals: sudo.approvals,\n capture: (request, where, context) => sudo.capture(request, where, context),\n async request(request, where, context) {\n forget();\n const asked = await sudo.request(request, where, context);\n if (asked.id) mine.add(asked.id);\n return asked;\n },\n async withdraw(id, reason, context) {\n if (!mine.delete(id)) return;\n await sudo.withdraw(id, reason, context);\n },\n release() {\n forget();\n for (const id of mine)\n void sudo.withdraw(id, REASONS.disconnected, BACKGROUND_CONTEXT).catch(() => undefined);\n mine.clear();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,0BAA0B;AAInC,SAAS,mBAAmB;AAE5B;AAAA,EAGE;AAAA,EACA;AAAA,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C;AAAA,IACA,UAAU;AACR,aAAO;AACP,iBAAW,MAAM;AACf,aAAK,KAAK,SAAS,IAAI,QAAQ,cAAc,kBAAkB,EAAE,MAAM,MAAM,MAAS;AACxF,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/attachments.js
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
1
|
const MIB = 1024 * 1024;
|
|
2
2
|
const IMAGE_LIMIT = 5 * MIB;
|
|
3
|
-
const
|
|
4
|
-
const
|
|
3
|
+
const INLINE_LIMIT = 8 * MIB;
|
|
4
|
+
const INLINE_TOTAL = 10 * MIB;
|
|
5
|
+
const FILE_LIMIT = 100 * MIB;
|
|
6
|
+
const TOTAL_LIMIT = 256 * MIB;
|
|
7
|
+
const STAGED_DIR = "/.slicc/attachments";
|
|
8
|
+
const STAGED_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
9
|
+
function stagedDir(serverId) {
|
|
10
|
+
return `${STAGED_DIR}/${serverId}`;
|
|
11
|
+
}
|
|
5
12
|
const SEEN = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
6
13
|
const BLIND = "This model can't see images, so the image was saved as a file instead.";
|
|
7
|
-
const
|
|
14
|
+
const UNSHOWN = "The image was too large to show the model, so it was saved as a file instead.";
|
|
8
15
|
function mib(bytes) {
|
|
9
16
|
return `${Math.round(bytes / MIB)} MiB`;
|
|
10
17
|
}
|
|
11
|
-
function
|
|
12
|
-
return
|
|
18
|
+
function together(limit) {
|
|
19
|
+
return `These attachments add up to more than ${mib(limit)}; send them in separate messages.`;
|
|
13
20
|
}
|
|
14
|
-
function tooLarge(name,
|
|
15
|
-
return `${name} is larger than ${mib(
|
|
21
|
+
function tooLarge(name, limit) {
|
|
22
|
+
return `${name} is larger than ${mib(limit)}, so it can't be sent.`;
|
|
16
23
|
}
|
|
17
24
|
function textBytes(text) {
|
|
18
25
|
return new TextEncoder().encode(text).length;
|
|
@@ -25,7 +32,7 @@ function fromBase64(data) {
|
|
|
25
32
|
}
|
|
26
33
|
const ESCAPES = { "&": "&", '"': """, "<": "<", ">": ">" };
|
|
27
34
|
function escape(value) {
|
|
28
|
-
return value.replace(/[&"<>]/g, (char) => ESCAPES[char]);
|
|
35
|
+
return value.replace(/\p{Cc}/gu, " ").replace(/[&"<>]/g, (char) => ESCAPES[char]);
|
|
29
36
|
}
|
|
30
37
|
function unescape(value) {
|
|
31
38
|
return value.replace(
|
|
@@ -106,61 +113,103 @@ function splitUser(content, prefix) {
|
|
|
106
113
|
}
|
|
107
114
|
return { text, attachments };
|
|
108
115
|
}
|
|
109
|
-
|
|
110
|
-
const size = decodedSize(data);
|
|
111
|
-
if (size > limitOf(attachment.kind)) throw new Error(tooLarge(attachment.name, attachment.kind));
|
|
116
|
+
function savedText(attachment, path, size, saver) {
|
|
112
117
|
const header = { kind: attachment.kind, name: attachment.name, type: attachment.mimeType };
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
if (!saver.save) throw new Error(`This agent can't save ${attachment.name} as a file.`);
|
|
119
|
-
const path = await saver.save(attachment.name, fromBase64(data));
|
|
120
|
-
const blind = attachment.kind === "image" && !saver.sees ? ` ${BLIND}` : "";
|
|
121
|
-
return [{ type: "text", text: wrap({ ...header, path, size }, `Saved at ${path}.${blind}`) }];
|
|
122
|
-
}
|
|
123
|
-
async function partsOf(attachment, saver) {
|
|
124
|
-
const header = {
|
|
125
|
-
kind: attachment.kind,
|
|
126
|
-
name: attachment.name,
|
|
127
|
-
type: attachment.mimeType,
|
|
128
|
-
...attachment.path === void 0 ? {} : { path: attachment.path }
|
|
118
|
+
const image = attachment.kind === "image";
|
|
119
|
+
const note = !image ? "" : !saver.sees ? ` ${BLIND}` : SEEN.has(attachment.mimeType) ? ` ${UNSHOWN}` : "";
|
|
120
|
+
return {
|
|
121
|
+
type: "text",
|
|
122
|
+
text: wrap({ ...header, path, size }, `Saved at ${escape(path)}.${note}`)
|
|
129
123
|
};
|
|
124
|
+
}
|
|
125
|
+
function shownImage(attachment, size, saver) {
|
|
126
|
+
return attachment.kind === "image" && saver.sees && SEEN.has(attachment.mimeType) && size <= IMAGE_LIMIT;
|
|
127
|
+
}
|
|
128
|
+
function saving(attachment, saver) {
|
|
129
|
+
if (!saver.save) throw new Error(`This agent can't save ${attachment.name} as a file.`);
|
|
130
|
+
}
|
|
131
|
+
async function planned(attachment, saver) {
|
|
130
132
|
if (attachment.kind === "text" && attachment.text !== void 0) {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
return
|
|
133
|
+
const size = textBytes(attachment.text);
|
|
134
|
+
if (size > INLINE_LIMIT) throw new Error(tooLarge(attachment.name, INLINE_LIMIT));
|
|
135
|
+
return { attachment, size };
|
|
134
136
|
}
|
|
135
|
-
if (attachment.data !== void 0)
|
|
136
|
-
|
|
137
|
-
|
|
137
|
+
if (attachment.data !== void 0) {
|
|
138
|
+
const size = decodedSize(attachment.data);
|
|
139
|
+
if (size > INLINE_LIMIT) throw new Error(tooLarge(attachment.name, INLINE_LIMIT));
|
|
140
|
+
if (!shownImage(attachment, size, saver)) saving(attachment, saver);
|
|
141
|
+
return { attachment, size };
|
|
142
|
+
}
|
|
143
|
+
if (attachment.upload !== void 0) {
|
|
144
|
+
const id = attachment.upload;
|
|
145
|
+
const blob = STAGED_ID.test(id) ? await saver.staging?.take(id) : void 0;
|
|
146
|
+
if (!blob) throw new Error(`Couldn't find ${attachment.name} again; attach it again.`);
|
|
147
|
+
if (blob.size > FILE_LIMIT) throw new Error(tooLarge(attachment.name, FILE_LIMIT));
|
|
148
|
+
saving(attachment, saver);
|
|
149
|
+
return { attachment, size: blob.size, blob };
|
|
150
|
+
}
|
|
151
|
+
if (attachment.path !== void 0) return { attachment, size: 0 };
|
|
138
152
|
throw new Error(`${attachment.name} has nothing to send.`);
|
|
139
153
|
}
|
|
154
|
+
async function partsOf({ attachment, size, blob }, saver) {
|
|
155
|
+
const base = { kind: attachment.kind, name: attachment.name, type: attachment.mimeType };
|
|
156
|
+
const header = { ...base, ...attachment.path === void 0 ? {} : { path: attachment.path } };
|
|
157
|
+
if (attachment.kind === "text" && attachment.text !== void 0)
|
|
158
|
+
return [{ type: "text", text: wrap(header, attachment.text) }];
|
|
159
|
+
const save = saver.save;
|
|
160
|
+
if (attachment.data !== void 0) {
|
|
161
|
+
if (shownImage(attachment, size, saver))
|
|
162
|
+
return [
|
|
163
|
+
{ type: "text", text: wrap(base, "") },
|
|
164
|
+
{ type: "image", data: attachment.data, mimeType: attachment.mimeType }
|
|
165
|
+
];
|
|
166
|
+
const path = await save(attachment.name, fromBase64(attachment.data));
|
|
167
|
+
return [savedText(attachment, path, size, saver)];
|
|
168
|
+
}
|
|
169
|
+
if (blob) {
|
|
170
|
+
const path = await save(attachment.name, new Uint8Array(await blob.arrayBuffer()));
|
|
171
|
+
return [savedText(attachment, path, size, saver)];
|
|
172
|
+
}
|
|
173
|
+
return [{ type: "text", text: wrap(header, `It is at ${escape(attachment.path)}.`) }];
|
|
174
|
+
}
|
|
140
175
|
async function userParts(text, attachments, saver) {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
176
|
+
try {
|
|
177
|
+
const inline = attachments.reduce(
|
|
178
|
+
(sum, item) => sum + textBytes(item.text ?? "") + decodedSize(item.data ?? ""),
|
|
179
|
+
0
|
|
180
|
+
);
|
|
181
|
+
if (inline > INLINE_TOTAL) throw new Error(together(INLINE_TOTAL));
|
|
182
|
+
const plans = [];
|
|
183
|
+
for (const attachment of attachments) plans.push(await planned(attachment, saver));
|
|
184
|
+
if (plans.reduce((sum, plan) => sum + plan.size, 0) > TOTAL_LIMIT)
|
|
185
|
+
throw new Error(together(TOTAL_LIMIT));
|
|
186
|
+
const parts = text ? [{ type: "text", text }] : [];
|
|
187
|
+
for (const plan of plans) parts.push(...await partsOf(plan, saver));
|
|
188
|
+
return parts;
|
|
189
|
+
} finally {
|
|
190
|
+
const ids = attachments.flatMap((item) => item.upload === void 0 ? [] : [item.upload]);
|
|
191
|
+
await Promise.all(ids.map((id) => saver.staging?.drop(id)));
|
|
192
|
+
}
|
|
149
193
|
}
|
|
150
194
|
export {
|
|
151
195
|
BLIND,
|
|
152
196
|
FILE_LIMIT,
|
|
153
197
|
IMAGE_LIMIT,
|
|
198
|
+
INLINE_LIMIT,
|
|
199
|
+
INLINE_TOTAL,
|
|
154
200
|
REF,
|
|
155
201
|
SEEN,
|
|
156
|
-
|
|
202
|
+
STAGED_DIR,
|
|
203
|
+
STAGED_ID,
|
|
157
204
|
TOTAL_LIMIT,
|
|
205
|
+
UNSHOWN,
|
|
158
206
|
decodedSize,
|
|
159
207
|
fromBase64,
|
|
160
|
-
limitOf,
|
|
161
208
|
mib,
|
|
162
209
|
splitUser,
|
|
210
|
+
stagedDir,
|
|
163
211
|
textBytes,
|
|
212
|
+
together,
|
|
164
213
|
tooLarge,
|
|
165
214
|
userParts,
|
|
166
215
|
wrap
|
package/dist/attachments.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/attachments.ts"],
|
|
4
|
-
"sourcesContent": ["export type AttachmentKind = 'image' | 'text' | 'file';\n\nexport interface SendAttachment {\n name: string;\n mimeType: string;\n kind: AttachmentKind;\n data?: string;\n text?: string;\n path?: string;\n}\n\nexport interface ShownAttachment {\n id: string;\n name: string;\n kind: AttachmentKind;\n mimeType: string;\n size: number;\n url?: string;\n text?: string;\n path?: string;\n}\n\nexport type Part =\n | { type: 'text'; text: string }\n | { type: 'image'; data: string; mimeType: string };\n\nexport interface Saver {\n sees: boolean;\n save?(name: string, bytes: Uint8Array): Promise<string>;\n}\n\nconst MIB = 1024 * 1024;\n\nexport const IMAGE_LIMIT = 5 * MIB;\nexport const FILE_LIMIT = 8 * MIB;\nexport const TOTAL_LIMIT = 10 * MIB;\n\nexport const SEEN = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);\n\nexport const BLIND = \"This model can't see images, so the image was saved as a file instead.\";\n\nexport const TOGETHER = `These attachments add up to more than ${TOTAL_LIMIT / MIB} MiB; send them in separate messages.`;\n\nexport function mib(bytes: number): string {\n return `${Math.round(bytes / MIB)} MiB`;\n}\n\nexport function limitOf(kind: AttachmentKind): number {\n return kind === 'image' ? IMAGE_LIMIT : FILE_LIMIT;\n}\n\nexport function tooLarge(name: string, kind: AttachmentKind): string {\n return `${name} is larger than ${mib(limitOf(kind))}, so it can't be sent.`;\n}\n\nexport function textBytes(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\nexport function decodedSize(data: string): number {\n return Math.floor((data.length * 3) / 4) - (data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0);\n}\n\nexport function fromBase64(data: string): Uint8Array {\n return Uint8Array.from(atob(data), (char) => char.charCodeAt(0));\n}\n\nconst ESCAPES: Record<string, string> = { '&': '&', '\"': '"', '<': '<', '>': '>' };\n\nfunction escape(value: string): string {\n return value.replace(/[&\"<>]/g, (char) => ESCAPES[char] as string);\n}\n\nfunction unescape(value: string): string {\n return value.replace(/&(amp|quot|lt|gt);/g, (_, name: string) =>\n name === 'amp' ? '&' : name === 'quot' ? '\"' : name === 'lt' ? '<' : '>'\n );\n}\n\ninterface Header {\n kind: AttachmentKind;\n name: string;\n type: string;\n path?: string;\n size?: number;\n}\n\nexport function wrap(header: Header, body: string): string {\n const path = header.path === undefined ? '' : ` path=\"${escape(header.path)}\"`;\n const size = header.size === undefined ? '' : ` size=\"${header.size}\"`;\n return `<attachment kind=\"${header.kind}\" name=\"${escape(header.name)}\" type=\"${escape(header.type)}\"${path}${size}>\\n${body}\\n</attachment>`;\n}\n\nconst WRAPPED =\n /^<attachment kind=\"(image|text|file)\" name=\"([^\"]*)\" type=\"([^\"]*)\"(?: path=\"([^\"]*)\")?(?: size=\"(\\d+)\")?>\\n([\\s\\S]*)\\n<\\/attachment>$/;\n\nfunction unwrap(text: string): (Header & { body: string }) | undefined {\n const match = WRAPPED.exec(text);\n if (!match) return undefined;\n const [, kind, name, type, path, size, body] = match as unknown as string[];\n return {\n kind: kind as AttachmentKind,\n name: unescape(name as string),\n type: unescape(type as string),\n ...(path === undefined ? {} : { path: unescape(path) }),\n ...(size === undefined ? {} : { size: Number(size) }),\n body: body as string,\n };\n}\n\ntype Block = {\n type?: string;\n text?: string;\n data?: string;\n mimeType?: string;\n full?: { mimeType: string; size: number };\n};\n\nexport const REF = /^ref:(\\d+):(\\d+):(\\d+)$/;\n\nfunction picture(base: Omit<ShownAttachment, 'size'>, block: Block, ref?: string): ShownAttachment {\n const url = block.data ? { url: `data:${block.mimeType};base64,${block.data}` } : {};\n if (!block.full) return { ...base, size: decodedSize(block.data ?? ''), ...url };\n return {\n ...base,\n ...(ref ? { id: ref } : {}),\n mimeType: block.full.mimeType,\n size: block.full.size,\n ...url,\n };\n}\n\nfunction shown(\n header: Header & { body: string },\n index: number,\n next?: Block,\n ref?: string\n): ShownAttachment {\n const base = {\n id: `a${index}`,\n name: header.name,\n kind: header.kind,\n mimeType: header.type,\n ...(header.path === undefined ? {} : { path: header.path }),\n };\n if (header.kind === 'text')\n return { ...base, size: header.size ?? header.body.length, text: header.body };\n if (next) return picture(base, next, ref);\n return { ...base, size: header.size ?? 0 };\n}\n\nexport function splitUser(\n content: unknown,\n prefix?: string\n): { text: string; attachments: ShownAttachment[] } {\n if (typeof content === 'string') return { text: content, attachments: [] };\n const blocks = Array.isArray(content) ? (content as Block[]) : [];\n const attachments: ShownAttachment[] = [];\n let text = '';\n for (let index = 0; index < blocks.length; index++) {\n const block = blocks[index] as Block;\n const header = block.type === 'text' ? unwrap(block.text ?? '') : undefined;\n const next = blocks[index + 1];\n const ref = (at: number) => (prefix ? `${prefix}:${at}` : undefined);\n if (header) {\n const image = header.kind === 'image' && next?.type === 'image' ? next : undefined;\n attachments.push(shown(header, attachments.length, image, ref(index + 1)));\n if (image) index++;\n } else if (block.type === 'text') text += block.text ?? '';\n else if (block.type === 'image' && (block.data || block.full))\n attachments.push(\n shown(\n { kind: 'image', name: 'image', type: String(block.mimeType), body: '' },\n attachments.length,\n block,\n ref(index)\n )\n );\n }\n return { text, attachments };\n}\n\nasync function encoded(attachment: SendAttachment, data: string, saver: Saver): Promise<Part[]> {\n const size = decodedSize(data);\n if (size > limitOf(attachment.kind)) throw new Error(tooLarge(attachment.name, attachment.kind));\n const header = { kind: attachment.kind, name: attachment.name, type: attachment.mimeType };\n if (attachment.kind === 'image' && saver.sees && SEEN.has(attachment.mimeType))\n return [\n { type: 'text', text: wrap(header, '') },\n { type: 'image', data, mimeType: attachment.mimeType },\n ];\n if (!saver.save) throw new Error(`This agent can't save ${attachment.name} as a file.`);\n const path = await saver.save(attachment.name, fromBase64(data));\n const blind = attachment.kind === 'image' && !saver.sees ? ` ${BLIND}` : '';\n return [{ type: 'text', text: wrap({ ...header, path, size }, `Saved at ${path}.${blind}`) }];\n}\n\nasync function partsOf(attachment: SendAttachment, saver: Saver): Promise<Part[]> {\n const header = {\n kind: attachment.kind,\n name: attachment.name,\n type: attachment.mimeType,\n ...(attachment.path === undefined ? {} : { path: attachment.path }),\n };\n if (attachment.kind === 'text' && attachment.text !== undefined) {\n if (textBytes(attachment.text) > FILE_LIMIT)\n throw new Error(tooLarge(attachment.name, attachment.kind));\n return [{ type: 'text', text: wrap(header, attachment.text) }];\n }\n if (attachment.data !== undefined) return encoded(attachment, attachment.data, saver);\n if (attachment.path !== undefined)\n return [{ type: 'text', text: wrap(header, `It is at ${attachment.path}.`) }];\n throw new Error(`${attachment.name} has nothing to send.`);\n}\n\nexport async function userParts(\n text: string,\n attachments: readonly SendAttachment[],\n saver: Saver\n): Promise<Part[]> {\n const total = attachments.reduce(\n (sum, item) => sum + textBytes(item.text ?? '') + decodedSize(item.data ?? ''),\n 0\n );\n if (total > TOTAL_LIMIT) throw new Error(TOGETHER);\n const parts: Part[] = text ? [{ type: 'text', text }] : [];\n for (const attachment of attachments) parts.push(...(await partsOf(attachment, saver)));\n return parts;\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["export type AttachmentKind = 'image' | 'text' | 'file';\n\nexport interface SendAttachment {\n name: string;\n mimeType: string;\n kind: AttachmentKind;\n data?: string;\n text?: string;\n path?: string;\n upload?: string;\n}\n\nexport interface ShownAttachment {\n id: string;\n name: string;\n kind: AttachmentKind;\n mimeType: string;\n size: number;\n url?: string;\n text?: string;\n path?: string;\n}\n\nexport type Part =\n | { type: 'text'; text: string }\n | { type: 'image'; data: string; mimeType: string };\n\nexport interface Saver {\n sees: boolean;\n save?(name: string, bytes: Uint8Array): Promise<string>;\n staging?: { take(id: string): Promise<Blob | undefined>; drop(id: string): Promise<void> };\n}\n\nconst MIB = 1024 * 1024;\n\nexport const IMAGE_LIMIT = 5 * MIB;\nexport const INLINE_LIMIT = 8 * MIB;\nexport const INLINE_TOTAL = 10 * MIB;\nexport const FILE_LIMIT = 100 * MIB;\nexport const TOTAL_LIMIT = 256 * MIB;\n\nexport const STAGED_DIR = '/.slicc/attachments';\n\nexport const STAGED_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nexport function stagedDir(serverId: string): string {\n return `${STAGED_DIR}/${serverId}`;\n}\n\nexport const SEEN = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);\n\nexport const BLIND = \"This model can't see images, so the image was saved as a file instead.\";\n\nexport const UNSHOWN =\n 'The image was too large to show the model, so it was saved as a file instead.';\n\nexport function mib(bytes: number): string {\n return `${Math.round(bytes / MIB)} MiB`;\n}\n\nexport function together(limit: number): string {\n return `These attachments add up to more than ${mib(limit)}; send them in separate messages.`;\n}\n\nexport function tooLarge(name: string, limit: number): string {\n return `${name} is larger than ${mib(limit)}, so it can't be sent.`;\n}\n\nexport function textBytes(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\nexport function decodedSize(data: string): number {\n return Math.floor((data.length * 3) / 4) - (data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0);\n}\n\nexport function fromBase64(data: string): Uint8Array {\n return Uint8Array.from(atob(data), (char) => char.charCodeAt(0));\n}\n\nconst ESCAPES: Record<string, string> = { '&': '&', '\"': '"', '<': '<', '>': '>' };\n\nfunction escape(value: string): string {\n return value.replace(/\\p{Cc}/gu, ' ').replace(/[&\"<>]/g, (char) => ESCAPES[char] as string);\n}\n\nfunction unescape(value: string): string {\n return value.replace(/&(amp|quot|lt|gt);/g, (_, name: string) =>\n name === 'amp' ? '&' : name === 'quot' ? '\"' : name === 'lt' ? '<' : '>'\n );\n}\n\ninterface Header {\n kind: AttachmentKind;\n name: string;\n type: string;\n path?: string;\n size?: number;\n}\n\nexport function wrap(header: Header, body: string): string {\n const path = header.path === undefined ? '' : ` path=\"${escape(header.path)}\"`;\n const size = header.size === undefined ? '' : ` size=\"${header.size}\"`;\n return `<attachment kind=\"${header.kind}\" name=\"${escape(header.name)}\" type=\"${escape(header.type)}\"${path}${size}>\\n${body}\\n</attachment>`;\n}\n\nconst WRAPPED =\n /^<attachment kind=\"(image|text|file)\" name=\"([^\"]*)\" type=\"([^\"]*)\"(?: path=\"([^\"]*)\")?(?: size=\"(\\d+)\")?>\\n([\\s\\S]*)\\n<\\/attachment>$/;\n\nfunction unwrap(text: string): (Header & { body: string }) | undefined {\n const match = WRAPPED.exec(text);\n if (!match) return undefined;\n const [, kind, name, type, path, size, body] = match as unknown as string[];\n return {\n kind: kind as AttachmentKind,\n name: unescape(name as string),\n type: unescape(type as string),\n ...(path === undefined ? {} : { path: unescape(path) }),\n ...(size === undefined ? {} : { size: Number(size) }),\n body: body as string,\n };\n}\n\ntype Block = {\n type?: string;\n text?: string;\n data?: string;\n mimeType?: string;\n full?: { mimeType: string; size: number };\n};\n\nexport const REF = /^ref:(\\d+):(\\d+):(\\d+)$/;\n\nfunction picture(base: Omit<ShownAttachment, 'size'>, block: Block, ref?: string): ShownAttachment {\n const url = block.data ? { url: `data:${block.mimeType};base64,${block.data}` } : {};\n if (!block.full) return { ...base, size: decodedSize(block.data ?? ''), ...url };\n return {\n ...base,\n ...(ref ? { id: ref } : {}),\n mimeType: block.full.mimeType,\n size: block.full.size,\n ...url,\n };\n}\n\nfunction shown(\n header: Header & { body: string },\n index: number,\n next?: Block,\n ref?: string\n): ShownAttachment {\n const base = {\n id: `a${index}`,\n name: header.name,\n kind: header.kind,\n mimeType: header.type,\n ...(header.path === undefined ? {} : { path: header.path }),\n };\n if (header.kind === 'text')\n return { ...base, size: header.size ?? header.body.length, text: header.body };\n if (next) return picture(base, next, ref);\n return { ...base, size: header.size ?? 0 };\n}\n\nexport function splitUser(\n content: unknown,\n prefix?: string\n): { text: string; attachments: ShownAttachment[] } {\n if (typeof content === 'string') return { text: content, attachments: [] };\n const blocks = Array.isArray(content) ? (content as Block[]) : [];\n const attachments: ShownAttachment[] = [];\n let text = '';\n for (let index = 0; index < blocks.length; index++) {\n const block = blocks[index] as Block;\n const header = block.type === 'text' ? unwrap(block.text ?? '') : undefined;\n const next = blocks[index + 1];\n const ref = (at: number) => (prefix ? `${prefix}:${at}` : undefined);\n if (header) {\n const image = header.kind === 'image' && next?.type === 'image' ? next : undefined;\n attachments.push(shown(header, attachments.length, image, ref(index + 1)));\n if (image) index++;\n } else if (block.type === 'text') text += block.text ?? '';\n else if (block.type === 'image' && (block.data || block.full))\n attachments.push(\n shown(\n { kind: 'image', name: 'image', type: String(block.mimeType), body: '' },\n attachments.length,\n block,\n ref(index)\n )\n );\n }\n return { text, attachments };\n}\n\nfunction savedText(attachment: SendAttachment, path: string, size: number, saver: Saver): Part {\n const header = { kind: attachment.kind, name: attachment.name, type: attachment.mimeType };\n const image = attachment.kind === 'image';\n const note = !image\n ? ''\n : !saver.sees\n ? ` ${BLIND}`\n : SEEN.has(attachment.mimeType)\n ? ` ${UNSHOWN}`\n : '';\n return {\n type: 'text',\n text: wrap({ ...header, path, size }, `Saved at ${escape(path)}.${note}`),\n };\n}\n\nfunction shownImage(attachment: SendAttachment, size: number, saver: Saver): boolean {\n return (\n attachment.kind === 'image' &&\n saver.sees &&\n SEEN.has(attachment.mimeType) &&\n size <= IMAGE_LIMIT\n );\n}\n\ninterface Plan {\n attachment: SendAttachment;\n size: number;\n blob?: Blob;\n}\n\nfunction saving(attachment: SendAttachment, saver: Saver): void {\n if (!saver.save) throw new Error(`This agent can't save ${attachment.name} as a file.`);\n}\n\nasync function planned(attachment: SendAttachment, saver: Saver): Promise<Plan> {\n if (attachment.kind === 'text' && attachment.text !== undefined) {\n const size = textBytes(attachment.text);\n if (size > INLINE_LIMIT) throw new Error(tooLarge(attachment.name, INLINE_LIMIT));\n return { attachment, size };\n }\n if (attachment.data !== undefined) {\n const size = decodedSize(attachment.data);\n if (size > INLINE_LIMIT) throw new Error(tooLarge(attachment.name, INLINE_LIMIT));\n if (!shownImage(attachment, size, saver)) saving(attachment, saver);\n return { attachment, size };\n }\n if (attachment.upload !== undefined) {\n const id = attachment.upload;\n const blob = STAGED_ID.test(id) ? await saver.staging?.take(id) : undefined;\n if (!blob) throw new Error(`Couldn't find ${attachment.name} again; attach it again.`);\n if (blob.size > FILE_LIMIT) throw new Error(tooLarge(attachment.name, FILE_LIMIT));\n saving(attachment, saver);\n return { attachment, size: blob.size, blob };\n }\n if (attachment.path !== undefined) return { attachment, size: 0 };\n throw new Error(`${attachment.name} has nothing to send.`);\n}\n\nasync function partsOf({ attachment, size, blob }: Plan, saver: Saver): Promise<Part[]> {\n const base = { kind: attachment.kind, name: attachment.name, type: attachment.mimeType };\n const header = { ...base, ...(attachment.path === undefined ? {} : { path: attachment.path }) };\n if (attachment.kind === 'text' && attachment.text !== undefined)\n return [{ type: 'text', text: wrap(header, attachment.text) }];\n const save = saver.save as NonNullable<Saver['save']>;\n if (attachment.data !== undefined) {\n if (shownImage(attachment, size, saver))\n return [\n { type: 'text', text: wrap(base, '') },\n { type: 'image', data: attachment.data, mimeType: attachment.mimeType },\n ];\n const path = await save(attachment.name, fromBase64(attachment.data));\n return [savedText(attachment, path, size, saver)];\n }\n if (blob) {\n const path = await save(attachment.name, new Uint8Array(await blob.arrayBuffer()));\n return [savedText(attachment, path, size, saver)];\n }\n return [{ type: 'text', text: wrap(header, `It is at ${escape(attachment.path as string)}.`) }];\n}\n\nexport async function userParts(\n text: string,\n attachments: readonly SendAttachment[],\n saver: Saver\n): Promise<Part[]> {\n try {\n const inline = attachments.reduce(\n (sum, item) => sum + textBytes(item.text ?? '') + decodedSize(item.data ?? ''),\n 0\n );\n if (inline > INLINE_TOTAL) throw new Error(together(INLINE_TOTAL));\n const plans: Plan[] = [];\n for (const attachment of attachments) plans.push(await planned(attachment, saver));\n if (plans.reduce((sum, plan) => sum + plan.size, 0) > TOTAL_LIMIT)\n throw new Error(together(TOTAL_LIMIT));\n const parts: Part[] = text ? [{ type: 'text', text }] : [];\n for (const plan of plans) parts.push(...(await partsOf(plan, saver)));\n return parts;\n } finally {\n const ids = attachments.flatMap((item) => (item.upload === undefined ? [] : [item.upload]));\n await Promise.all(ids.map((id) => saver.staging?.drop(id)));\n }\n}\n"],
|
|
5
|
+
"mappings": "AAiCA,MAAM,MAAM,OAAO;AAEZ,MAAM,cAAc,IAAI;AACxB,MAAM,eAAe,IAAI;AACzB,MAAM,eAAe,KAAK;AAC1B,MAAM,aAAa,MAAM;AACzB,MAAM,cAAc,MAAM;AAE1B,MAAM,aAAa;AAEnB,MAAM,YAAY;AAElB,SAAS,UAAU,UAA0B;AAClD,SAAO,GAAG,UAAU,IAAI,QAAQ;AAClC;AAEO,MAAM,OAAO,oBAAI,IAAI,CAAC,aAAa,cAAc,aAAa,YAAY,CAAC;AAE3E,MAAM,QAAQ;AAEd,MAAM,UACX;AAEK,SAAS,IAAI,OAAuB;AACzC,SAAO,GAAG,KAAK,MAAM,QAAQ,GA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ACiB;AACjB,MAAI;AACF,UAAM,SAAS,YAAY;AAAA,MACzB,CAAC,KAAK,SAAS,MAAM,UAAU,KAAK,QAAQ,EAAE,IAAI,YAAY,KAAK,QAAQ,EAAE;AAAA,MAC7E;AAAA,IACF;AACA,QAAI,SAAS,aAAc,OAAM,IAAI,MAAM,SAAS,YAAY,CAAC;AACjE,UAAM,QAAgB,CAAC;AACvB,eAAW,cAAc,YAAa,OAAM,KAAK,MAAM,QAAQ,YAAY,KAAK,CAAC;AACjF,QAAI,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,KAAK,MAAM,CAAC,IAAI;AACpD,YAAM,IAAI,MAAM,SAAS,WAAW,CAAC;AACvC,UAAM,QAAgB,OAAO,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC,IAAI,CAAC;AACzD,eAAW,QAAQ,MAAO,OAAM,KAAK,GAAI,MAAM,QAAQ,MAAM,KAAK,CAAE;AACpE,WAAO;AAAA,EACT,UAAE;AACA,UAAM,MAAM,YAAY,QAAQ,CAAC,SAAU,KAAK,WAAW,SAAY,CAAC,IAAI,CAAC,KAAK,MAAM,CAAE;AAC1F,UAAM,QAAQ,IAAI,IAAI,IAAI,CAAC,OAAO,MAAM,SAAS,KAAK,EAAE,CAAC,CAAC;AAAA,EAC5D;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["export {\n ADOBE,\n ADOBE_PROXY,\n type AdobeConfig,\n type AdobeModelInfo,\n adobeClassifiers,\n adobeConfig,\n adobeIdentity,\n adobeModel,\n adobeProvider,\n adobeUsage,\n type Budget,\n SESSION_HEADER,\n VERSION_HEADER,\n withAdobeIdentity,\n} from './adobe.ts';\nexport { type Agent, type AgentOptions, answerText, openAgent } from './agent.ts';\nexport {\n APPROVAL_MS,\n type Approval,\n type ApprovalAnswer,\n type ApprovalDecided,\n type ApprovalDraft,\n type ApprovalJudge,\n type ApprovalKind,\n type ApprovalRequester,\n type ApprovalState,\n type Approvals,\n ApprovalsDoc,\n type ApprovalTier,\n type ApprovalVerdict,\n ASK_MIN_MS,\n approvalJudge,\n attachApprovals,\n type CaptureApproval,\n type CaptureDetail,\n DEFAULT_POLICY,\n type DecidedBy,\n type Decider,\n JUDGE_ALLOW,\n JUDGE_KIND,\n JUDGE_MODEL,\n JUDGE_QUESTIONS,\n type Judgement,\n judgeModelOf,\n judgeSpender,\n judgeState,\n type OwnerIntent,\n ownerIntent,\n POLICY_FILE,\n REASONS,\n route,\n seedPolicy,\n VERDICT_REASONS,\n verdictOf,\n verdictRecorder,\n} from './approvals/index.ts';\nexport {\n type ApprovalPolicy,\n type ApprovalPolicyChange,\n type ApprovalPolicySet,\n DEFAULT_APPROVAL_POLICY,\n type SudoPolicy,\n} from './approvals/policy.ts';\nexport type {\n AgentSudo,\n SudoAnswer,\n SudoDenial,\n SudoReply,\n SudoRequest,\n} from './approvals/sudo.ts';\nexport type { CaptureAsk } from './approvals/sudo-client.ts';\nexport {\n FILE_LIMIT,\n IMAGE_LIMIT,\n type SendAttachment,\n type ShownAttachment,\n splitUser,\n TOTAL_LIMIT,\n userParts,\n} from './attachments.ts';\nexport { type AgentConnection, connectAgent } from './client.ts';\nexport type { Clock } from './clock.ts';\nexport { createAgentControl } from './control.ts';\nexport type { CaptureAnswer, CaptureDenial, CaptureReply } from './guests/capture.ts';\nexport {\n connectGuest,\n GUEST_ONLY,\n type GuestConnection,\n SEAT_REFUSED,\n} from './guests/client.ts';\nexport type { GuestOpened, Proposed, ProposeRequest } from './guests/index.ts';\nexport type { GateKind, GuestPolicy } from './guests/policy.ts';\nexport type {\n AlwaysCapture,\n GuestDraft,\n GuestGate,\n GuestGates,\n GuestSeat,\n} from './guests/seats.ts';\nexport { type AgentHost, type ConnectOptions, hostAgent } from './host.ts';\nexport type {\n KernelClient,\n KernelFs,\n KernelProcess,\n KernelStat,\n SpawnOptions,\n} from './kernel/client.ts';\nexport { HOME, type KernelEnvOptions, kernelEnvironment, SliccKernelEnv } from './kernel/env.ts';\nexport {\n adminOver,\n type KernelAdmin,\n type KernelGroup,\n type KernelGroups,\n type KernelUser,\n type KernelUsers,\n serveAdmin,\n type UserClient,\n type UserClients,\n type UserConnect,\n type UserSpec,\n userClients,\n} from './kernel/users.ts';\nexport {\n type AgentWorkerOptions,\n type AgentWorkerScope,\n type KernelAttach,\n runAgentWorker,\n} from './main.ts';\nexport {\n type Loopback,\n type Transport,\n type TransportResponse,\n transportFetch,\n} from './net.ts';\nexport {\n AGENT_LOCK,\n type AgentOwner,\n type AgentWorker,\n type KernelSource,\n type OwnerOptions,\n startAgent,\n} from './owner.ts';\nexport { SliccPrompt, sliccPrompt } from './prompt.ts';\nexport {\n type AgentPages,\n createPages,\n type PageBatch,\n type PageCaller,\n type PageRequest,\n type PageResult,\n type Pages,\n type PagesOpened,\n type PageTab,\n} from './remote/pages.ts';\nexport {\n type AccountState,\n AgentControl,\n type AgentInventory,\n AgentInventoryService,\n AgentPagesService,\n AgentSettings,\n type AgentSettingsChange,\n AgentTranscript,\n type BudgetState,\n INVENTORY_STATUSES,\n type InventoryAgent,\n type InventoryRow,\n type InventorySnapshot,\n type InventoryState,\n type InventoryStatus,\n type McpEdit,\n type McpRefusal,\n type McpRefusalCode,\n type McpRefusals,\n type ModelChoice,\n type OperationError,\n type PromptResult,\n type SendMode,\n type SendRequest,\n type SendResponse,\n type SettingsState,\n type SignIn,\n} from './services.ts';\nexport {\n BEDROCK,\n createAgentSettings,\n createSliccModels,\n DEFAULT_MODEL,\n DEFAULT_REGIONS,\n PREFERRED_MODELS,\n preferredModel,\n resolveDefaultModel,\n sliccProviders,\n withDefaultRegions,\n} from './settings.ts';\nexport {\n AGENT_DIRECTORY,\n type OpfsSqliteOptions,\n openMemorySqliteStorage,\n openOpfsSqliteStorage,\n WasmSqliteDatabase,\n} from './sqlite.ts';\nexport { type SystemFacts, systemSection } from './system.ts';\nexport { UPLOADS, type Uploads, upload } from './uploads.ts';\nexport { type PortEndpoint, PortLink } from './wire.ts';\nexport {\n type KernelPorts,\n kernelPort,\n kernelPorts,\n serveConnections,\n type WorkerScope,\n} from './worker.ts';\n"],
|
|
5
|
-
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAwC,YAAY,iBAAiB;AACrE;AAAA,EACE;AAAA,EAUA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EAIE;AAAA,OAEK;
|
|
4
|
+
"sourcesContent": ["export {\n ADOBE,\n ADOBE_PROXY,\n type AdobeConfig,\n type AdobeModelInfo,\n adobeClassifiers,\n adobeConfig,\n adobeIdentity,\n adobeModel,\n adobeProvider,\n adobeUsage,\n type Budget,\n SESSION_HEADER,\n VERSION_HEADER,\n withAdobeIdentity,\n} from './adobe.ts';\nexport { type Agent, type AgentOptions, answerText, openAgent } from './agent.ts';\nexport {\n APPROVAL_MS,\n type Approval,\n type ApprovalAnswer,\n type ApprovalDecided,\n type ApprovalDraft,\n type ApprovalJudge,\n type ApprovalKind,\n type ApprovalRequester,\n type ApprovalState,\n type Approvals,\n ApprovalsDoc,\n type ApprovalTier,\n type ApprovalVerdict,\n ASK_MIN_MS,\n approvalJudge,\n attachApprovals,\n type CaptureApproval,\n type CaptureDetail,\n DEFAULT_POLICY,\n type DecidedBy,\n type Decider,\n JUDGE_ALLOW,\n JUDGE_KIND,\n JUDGE_MODEL,\n JUDGE_QUESTIONS,\n type Judgement,\n judgeModelOf,\n judgeSpender,\n judgeState,\n type OwnerIntent,\n ownerIntent,\n POLICY_FILE,\n REASONS,\n route,\n seedPolicy,\n VERDICT_REASONS,\n verdictOf,\n verdictRecorder,\n} from './approvals/index.ts';\nexport {\n type ApprovalPolicy,\n type ApprovalPolicyChange,\n type ApprovalPolicySet,\n DEFAULT_APPROVAL_POLICY,\n type SudoPolicy,\n} from './approvals/policy.ts';\nexport type {\n AgentSudo,\n SudoAnswer,\n SudoDenial,\n SudoReply,\n SudoRequest,\n SudoTimestamp,\n} from './approvals/sudo.ts';\nexport type { CaptureAsk } from './approvals/sudo-client.ts';\nexport {\n FILE_LIMIT,\n IMAGE_LIMIT,\n type SendAttachment,\n type ShownAttachment,\n splitUser,\n TOTAL_LIMIT,\n userParts,\n} from './attachments.ts';\nexport { type AgentConnection, connectAgent } from './client.ts';\nexport type { Clock } from './clock.ts';\nexport { createAgentControl } from './control.ts';\nexport type { CaptureAnswer, CaptureDenial, CaptureReply } from './guests/capture.ts';\nexport {\n connectGuest,\n GUEST_ONLY,\n type GuestConnection,\n SEAT_REFUSED,\n} from './guests/client.ts';\nexport type { GuestOpened, Proposed, ProposeRequest } from './guests/index.ts';\nexport type { GateKind, GuestPolicy } from './guests/policy.ts';\nexport type {\n AlwaysCapture,\n GuestDraft,\n GuestGate,\n GuestGates,\n GuestSeat,\n} from './guests/seats.ts';\nexport { type AgentHost, type ConnectOptions, hostAgent } from './host.ts';\nexport type {\n KernelClient,\n KernelFs,\n KernelProcess,\n KernelStat,\n SpawnOptions,\n} from './kernel/client.ts';\nexport { HOME, type KernelEnvOptions, kernelEnvironment, SliccKernelEnv } from './kernel/env.ts';\nexport {\n adminOver,\n type KernelAdmin,\n type KernelGroup,\n type KernelGroups,\n type KernelUser,\n type KernelUsers,\n serveAdmin,\n type UserClient,\n type UserClients,\n type UserConnect,\n type UserSpec,\n userClients,\n} from './kernel/users.ts';\nexport {\n type AgentWorkerOptions,\n type AgentWorkerScope,\n type KernelAttach,\n runAgentWorker,\n} from './main.ts';\nexport {\n type Loopback,\n type Transport,\n type TransportResponse,\n transportFetch,\n} from './net.ts';\nexport {\n AGENT_LOCK,\n type AgentOwner,\n type AgentWorker,\n type KernelSource,\n type OwnerOptions,\n startAgent,\n} from './owner.ts';\nexport { SliccPrompt, sliccPrompt } from './prompt.ts';\nexport {\n type AgentPages,\n createPages,\n type PageBatch,\n type PageCaller,\n type PageRequest,\n type PageResult,\n type Pages,\n type PagesOpened,\n type PageTab,\n} from './remote/pages.ts';\nexport {\n type AccountState,\n AgentControl,\n type AgentInventory,\n AgentInventoryService,\n AgentPagesService,\n AgentSettings,\n type AgentSettingsChange,\n AgentTranscript,\n type BudgetState,\n INVENTORY_STATUSES,\n type InventoryAgent,\n type InventoryRow,\n type InventorySnapshot,\n type InventoryState,\n type InventoryStatus,\n type McpEdit,\n type McpRefusal,\n type McpRefusalCode,\n type McpRefusals,\n type ModelChoice,\n type OperationError,\n type PromptResult,\n type SendMode,\n type SendRequest,\n type SendResponse,\n type SettingsState,\n type SignIn,\n} from './services.ts';\nexport {\n BEDROCK,\n createAgentSettings,\n createSliccModels,\n DEFAULT_MODEL,\n DEFAULT_REGIONS,\n PREFERRED_MODELS,\n preferredModel,\n resolveDefaultModel,\n sliccProviders,\n withDefaultRegions,\n} from './settings.ts';\nexport {\n AGENT_DIRECTORY,\n type OpfsSqliteOptions,\n openMemorySqliteStorage,\n openOpfsSqliteStorage,\n WasmSqliteDatabase,\n} from './sqlite.ts';\nexport { type SystemFacts, systemSection } from './system.ts';\nexport { UPLOADS, type Uploads, upload } from './uploads.ts';\nexport { type PortEndpoint, PortLink } from './wire.ts';\nexport {\n type KernelPorts,\n kernelPort,\n kernelPorts,\n serveConnections,\n type WorkerScope,\n} from './worker.ts';\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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main.js
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
seedPolicy,
|
|
18
18
|
verdictRecorder
|
|
19
19
|
} from "./approvals/index.js";
|
|
20
|
+
import { STAGED_DIR, stagedDir } from "./attachments.js";
|
|
20
21
|
import { attachChanges, CHANGES_MS } from "./changes/index.js";
|
|
21
22
|
import {
|
|
22
23
|
codemodeExtension,
|
|
@@ -76,6 +77,7 @@ import {
|
|
|
76
77
|
import { RELOAD_MS, setupSkills } from "./skills/index.js";
|
|
77
78
|
import { setupSprinkles } from "./sprinkles/index.js";
|
|
78
79
|
import { openOpfsSqliteStorage } from "./sqlite.js";
|
|
80
|
+
import { workerStaging } from "./staging.js";
|
|
79
81
|
import {
|
|
80
82
|
agentVersion,
|
|
81
83
|
browserConnected,
|
|
@@ -98,7 +100,7 @@ function usersOf(admin, wanted, attach) {
|
|
|
98
100
|
const STORE_DIR = "/.slicc";
|
|
99
101
|
const ACCOUNTS_FILE = `${STORE_DIR}/accounts.json`;
|
|
100
102
|
const MODELS_FILE = `${STORE_DIR}/models.json`;
|
|
101
|
-
async function attached(ports, options) {
|
|
103
|
+
async function attached(ports, options, serverId) {
|
|
102
104
|
const wiped = await wipeLegacy();
|
|
103
105
|
const attach = options.attach ?? attachKernel;
|
|
104
106
|
const { kernel, admin } = await ports;
|
|
@@ -106,7 +108,7 @@ async function attached(ports, options) {
|
|
|
106
108
|
const users = usersOf(admin, options.users, attach);
|
|
107
109
|
await warnSupport(users, client, options.users);
|
|
108
110
|
const home = new SliccKernelEnv(client, { cwd: HOME });
|
|
109
|
-
await privateStore(home);
|
|
111
|
+
await privateStore(home, serverId);
|
|
110
112
|
return {
|
|
111
113
|
client,
|
|
112
114
|
users,
|
|
@@ -115,8 +117,12 @@ async function attached(ports, options) {
|
|
|
115
117
|
at: { home: HOME, ...users ? { agentDir: AGENT_DIR } : {} }
|
|
116
118
|
};
|
|
117
119
|
}
|
|
118
|
-
function privateStore(env) {
|
|
119
|
-
return env.exec(
|
|
120
|
+
function privateStore(env, serverId) {
|
|
121
|
+
return env.exec(
|
|
122
|
+
`mkdir -p ${STORE_DIR} && chmod 700 ${STORE_DIR} && rm -rf ${STAGED_DIR} && mkdir -p ${stagedDir(serverId)}`,
|
|
123
|
+
void 0,
|
|
124
|
+
BACKGROUND_CONTEXT
|
|
125
|
+
);
|
|
120
126
|
}
|
|
121
127
|
async function codemodeTools(client, options, native, extra, dir = `${HOME}/.pi/agent`) {
|
|
122
128
|
const settings = await client.fs.readFile(`${dir}/settings.json`).catch(() => void 0);
|
|
@@ -356,7 +362,8 @@ function kernelParts(client) {
|
|
|
356
362
|
return [createActivity(), processGroups(client), backgroundJobs(client)];
|
|
357
363
|
}
|
|
358
364
|
async function start(scope, ports, options, vault) {
|
|
359
|
-
const
|
|
365
|
+
const serverId = crypto.randomUUID();
|
|
366
|
+
const { client, users, home, at, wiped } = await attached(ports, options, serverId);
|
|
360
367
|
const ready = await prepare(scope, { client, home, vault }, options);
|
|
361
368
|
const { names, native, transport, facts, models, registry, records, endpoints } = ready;
|
|
362
369
|
const memory = setupMemory(registry);
|
|
@@ -485,7 +492,9 @@ async function start(scope, ports, options, vault) {
|
|
|
485
492
|
...options.catalog ? { catalog: options.catalog } : {}
|
|
486
493
|
});
|
|
487
494
|
await memoryRuntime.reload(BACKGROUND_CONTEXT).catch(() => void 0);
|
|
488
|
-
|
|
495
|
+
const staging = workerStaging(serverId, { maxAgeMs: options.stagedMs });
|
|
496
|
+
const host = await hostAgent(agent, {
|
|
497
|
+
serverId,
|
|
489
498
|
...await setupApprovals(models, home, at, agent, memoryRuntime.memories, options),
|
|
490
499
|
settings,
|
|
491
500
|
licks: { licks: licks.licks, sources },
|
|
@@ -502,7 +511,8 @@ async function start(scope, ports, options, vault) {
|
|
|
502
511
|
secrets: hostSecrets(vault, names, [names, records, endpoints]),
|
|
503
512
|
uploads: {
|
|
504
513
|
env: environment,
|
|
505
|
-
sees: (ref) => seesImages(models, ref)
|
|
514
|
+
sees: (ref) => seesImages(models, ref),
|
|
515
|
+
staging
|
|
506
516
|
},
|
|
507
517
|
monitor: {
|
|
508
518
|
kernel: client,
|
|
@@ -510,6 +520,16 @@ async function start(scope, ports, options, vault) {
|
|
|
510
520
|
...users ? { users: () => users.users.list() } : {}
|
|
511
521
|
}
|
|
512
522
|
});
|
|
523
|
+
return closing(host, staging);
|
|
524
|
+
}
|
|
525
|
+
function closing(host, staging) {
|
|
526
|
+
const close = host.close;
|
|
527
|
+
return Object.assign(host, {
|
|
528
|
+
close: () => {
|
|
529
|
+
staging.close();
|
|
530
|
+
return close();
|
|
531
|
+
}
|
|
532
|
+
});
|
|
513
533
|
}
|
|
514
534
|
function alive(client) {
|
|
515
535
|
return async (pid) => {
|