@hachej/boring-agent 0.1.111 → 0.2.1

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 (156) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +262 -51
  3. package/dist/agents.d.ts +75 -0
  4. package/dist/agents.js +91 -0
  5. package/dist/approval.d.ts +71 -0
  6. package/dist/approval.js +126 -0
  7. package/dist/artifacts.d.ts +53 -0
  8. package/dist/artifacts.js +129 -0
  9. package/dist/ask-user.d.ts +40 -0
  10. package/dist/ask-user.js +134 -0
  11. package/dist/attachment.d.ts +5 -0
  12. package/dist/attachment.js +4 -0
  13. package/dist/browser-task.d.ts +32 -0
  14. package/dist/browser-task.js +119 -0
  15. package/dist/chat-transport.d.ts +80 -0
  16. package/dist/chat-transport.js +306 -0
  17. package/dist/contracts.d.ts +40 -0
  18. package/dist/contracts.js +1 -0
  19. package/dist/conversations.d.ts +136 -0
  20. package/dist/conversations.js +366 -0
  21. package/dist/definitions.d.ts +37 -0
  22. package/dist/definitions.js +99 -0
  23. package/dist/delivery-input.d.ts +35 -0
  24. package/dist/delivery-input.js +56 -0
  25. package/dist/delivery.d.ts +33 -0
  26. package/dist/delivery.js +154 -0
  27. package/dist/durable-wait.d.ts +23 -0
  28. package/dist/durable-wait.js +79 -0
  29. package/dist/file-convert.d.ts +46 -0
  30. package/dist/file-convert.js +159 -0
  31. package/dist/file-guard.d.ts +50 -0
  32. package/dist/file-guard.js +177 -0
  33. package/dist/file-types.d.ts +17 -0
  34. package/dist/file-types.js +95 -0
  35. package/dist/gateway-provider.d.ts +24 -0
  36. package/dist/gateway-provider.js +42 -0
  37. package/dist/git.d.ts +34 -0
  38. package/dist/git.js +79 -0
  39. package/dist/harness-pool.d.ts +38 -0
  40. package/dist/harness-pool.js +134 -0
  41. package/dist/index.d.ts +4 -0
  42. package/dist/index.js +1 -0
  43. package/dist/json-schema-tool.d.ts +25 -0
  44. package/dist/json-schema-tool.js +19 -0
  45. package/dist/memory/optchat-core.d.ts +118 -0
  46. package/dist/memory/optchat-core.js +317 -0
  47. package/dist/memory/optchat.d.ts +156 -0
  48. package/dist/memory/optchat.js +432 -0
  49. package/dist/mentions.d.ts +56 -0
  50. package/dist/mentions.js +140 -0
  51. package/dist/metering.d.ts +183 -0
  52. package/dist/metering.js +443 -0
  53. package/dist/model-gateway.d.ts +86 -0
  54. package/dist/model-gateway.js +241 -0
  55. package/dist/native-version.d.ts +9 -0
  56. package/dist/native-version.js +7 -0
  57. package/dist/native.d.ts +4 -0
  58. package/dist/native.js +1 -0
  59. package/dist/presentation.d.ts +17 -0
  60. package/dist/presentation.js +39 -0
  61. package/dist/projection-format.d.ts +68 -0
  62. package/dist/projection-format.js +118 -0
  63. package/dist/projection-window.d.ts +9 -0
  64. package/dist/projection-window.js +93 -0
  65. package/dist/projection.d.ts +22 -0
  66. package/dist/projection.js +153 -0
  67. package/dist/question-response.d.ts +20 -0
  68. package/dist/question-response.js +75 -0
  69. package/dist/questions.d.ts +74 -0
  70. package/dist/questions.js +199 -0
  71. package/dist/self-evolving.d.ts +55 -0
  72. package/dist/self-evolving.js +239 -0
  73. package/dist/skills.d.ts +15 -0
  74. package/dist/skills.js +51 -0
  75. package/dist/tool-evidence.d.ts +14 -0
  76. package/dist/tool-evidence.js +54 -0
  77. package/dist/validation.d.ts +38 -0
  78. package/dist/validation.js +68 -0
  79. package/dist/workspaces.d.ts +107 -0
  80. package/dist/workspaces.js +212 -0
  81. package/package.json +145 -150
  82. package/dist/DebugDrawer-JNA43SVR.js +0 -8
  83. package/dist/admin-DORVQfLn.d.ts +0 -340
  84. package/dist/chunk-2BGLZZ7T.js +0 -10
  85. package/dist/chunk-42D6KAQV.js +0 -2882
  86. package/dist/chunk-4XOW57KJ.js +0 -343
  87. package/dist/chunk-72KT6VWV.js +0 -1338
  88. package/dist/chunk-7XAOVFSN.js +0 -28
  89. package/dist/chunk-KJIEMSQP.js +0 -198
  90. package/dist/chunk-KN72XWP7.js +0 -394
  91. package/dist/chunk-N6THTH7P.js +0 -110
  92. package/dist/chunk-V3H5A3BR.js +0 -22501
  93. package/dist/chunk-YGRQ4Q5P.js +0 -20
  94. package/dist/chunk-YTUZFKB3.js +0 -78
  95. package/dist/core/index.d.ts +0 -28
  96. package/dist/core/index.js +0 -617
  97. package/dist/createHarness-DOLOHA62.js +0 -18
  98. package/dist/eval/index.d.ts +0 -247
  99. package/dist/eval/index.js +0 -541
  100. package/dist/file-search-BUgMSKZE.d.ts +0 -289
  101. package/dist/front/artifacts.d.ts +0 -34
  102. package/dist/front/artifacts.js +0 -21
  103. package/dist/front/index.d.ts +0 -1082
  104. package/dist/front/index.js +0 -12912
  105. package/dist/front/styles.css +0 -5380
  106. package/dist/harness-qHlMJhZo.d.ts +0 -276
  107. package/dist/middleware-CaAEXpi5.d.ts +0 -115
  108. package/dist/piChatEvent-DpE0lIb9.d.ts +0 -450
  109. package/dist/piChatSessionService-CBct-hmz.d.ts +0 -86
  110. package/dist/sandbox-BMhut3kh.d.ts +0 -317
  111. package/dist/server/agent-host/testing/compositionRouteProof.d.ts +0 -8
  112. package/dist/server/agent-host/testing/compositionRouteProof.js +0 -78
  113. package/dist/server/agent-host/testing/gatewayConformance.d.ts +0 -43
  114. package/dist/server/agent-host/testing/gatewayConformance.js +0 -605
  115. package/dist/server/index.d.ts +0 -2278
  116. package/dist/server/index.js +0 -274
  117. package/dist/server/pi-session-readability.d.ts +0 -12
  118. package/dist/server/pi-session-readability.js +0 -23
  119. package/dist/server/worker/index.d.ts +0 -68
  120. package/dist/server/worker/index.js +0 -377
  121. package/dist/share-entry-CxS6UJ_L.d.ts +0 -330
  122. package/dist/shared/index.d.ts +0 -2111
  123. package/dist/shared/index.js +0 -262
  124. package/dist/types-DcWoQMn8.d.ts +0 -1377
  125. package/docs/ACCESSIBILITY.md +0 -52
  126. package/docs/AGENT_GATEWAY_V0.md +0 -212
  127. package/docs/AGENT_PACKAGES.md +0 -90
  128. package/docs/API.md +0 -123
  129. package/docs/AUTHORING.md +0 -68
  130. package/docs/CSP.md +0 -41
  131. package/docs/ERROR_CODES.md +0 -229
  132. package/docs/KNOWN_LIMITATIONS.md +0 -100
  133. package/docs/MIGRATION.md +0 -50
  134. package/docs/PERFORMANCE.md +0 -68
  135. package/docs/PLUGINS.md +0 -138
  136. package/docs/README.md +0 -98
  137. package/docs/RISKS-MULTI-TAB.md +0 -46
  138. package/docs/SESSION_IDENTITY.md +0 -91
  139. package/docs/STYLING.md +0 -73
  140. package/docs/UI-SHADCN.md +0 -56
  141. package/docs/VERCEL_COSTS.md +0 -103
  142. package/docs/plans/archive/AGENT_EVAL_FRAMEWORK.md +0 -466
  143. package/docs/plans/archive/agent-package-spec.md +0 -1777
  144. package/docs/plans/archive/harness-followup-capabilities.md +0 -440
  145. package/docs/plans/archive/harness-tool-ui-capabilities.md +0 -144
  146. package/docs/plans/archive/pi-followup-history-projection.md +0 -229
  147. package/docs/plans/archive/pi-tools-migration.md +0 -1061
  148. package/docs/plans/archive/reviews/pi-followup-history-codex-review.md +0 -11
  149. package/docs/plans/archive/reviews/pi-followup-history-gpt-review.md +0 -64
  150. package/docs/plans/archive/reviews/pi-followup-history-opus-review.md +0 -43
  151. package/docs/plans/archive/reviews/pi-followup-history-xai-review.md +0 -43
  152. package/docs/plans/archive/vercel-base-snapshot-template-plan.md +0 -527
  153. package/docs/plans/archive/vercel-persistent-sandbox-adapter.md +0 -553
  154. package/docs/runtime-provisioning.md +0 -157
  155. package/docs/runtime.md +0 -296
  156. package/docs/tools.md +0 -102
@@ -1,617 +0,0 @@
1
- import {
2
- AGENT_NOT_IMPLEMENTED_UNTIL_T1,
3
- AgentNotImplementedError
4
- } from "../chunk-YTUZFKB3.js";
5
- import {
6
- ErrorCode
7
- } from "../chunk-KJIEMSQP.js";
8
-
9
- // src/core/piChatSessionService.ts
10
- var AgentEffectAdmissionError = class extends Error {
11
- constructor(code, details) {
12
- super(code);
13
- this.code = code;
14
- this.details = details;
15
- this.name = "AgentEffectAdmissionError";
16
- }
17
- code;
18
- details;
19
- statusCode = 500;
20
- };
21
- var observedSynchronousServiceErrors = /* @__PURE__ */ new WeakSet();
22
- function invokeObservedServiceEffect(effect) {
23
- try {
24
- return effect();
25
- } catch (error) {
26
- if (typeof error === "object" && error !== null || typeof error === "function") {
27
- observedSynchronousServiceErrors.add(error);
28
- }
29
- throw error;
30
- }
31
- }
32
- var AGENT_EFFECT_METHODS = {
33
- createSession: true,
34
- deleteSession: true,
35
- prompt: true,
36
- followUp: true,
37
- clearQueue: true,
38
- interrupt: true,
39
- stop: true
40
- };
41
- function withAgentEffectAdmission(service, admit) {
42
- return {
43
- ...service.resolveSessionStreamPath ? { resolveSessionStreamPath: (ctx, sessionId) => service.resolveSessionStreamPath(ctx, sessionId) } : {},
44
- ...service.ensurePiSessionBound ? { ensurePiSessionBound: (ctx, sessionId) => service.ensurePiSessionBound(ctx, sessionId) } : {},
45
- ...service.listSessions ? { listSessions: (ctx, options) => service.listSessions(ctx, options) } : {},
46
- async createSession(ctx, init) {
47
- await admit(ctx);
48
- return invokeObservedServiceEffect(() => service.createSession(ctx, init));
49
- },
50
- async deleteSession(ctx, sessionId) {
51
- await admit(ctx);
52
- return invokeObservedServiceEffect(() => service.deleteSession(ctx, sessionId));
53
- },
54
- ...service.readAttachment ? { readAttachment: (ctx, sessionId, messageId, index) => service.readAttachment(ctx, sessionId, messageId, index) } : {},
55
- readState: (ctx, sessionId) => service.readState(ctx, sessionId),
56
- subscribe: (ctx, sessionId, cursor, subscriber) => service.subscribe(ctx, sessionId, cursor, subscriber),
57
- async prompt(ctx, sessionId, payload) {
58
- await admit(ctx);
59
- return invokeObservedServiceEffect(() => service.prompt(ctx, sessionId, payload));
60
- },
61
- async followUp(ctx, sessionId, payload) {
62
- await admit(ctx);
63
- return invokeObservedServiceEffect(() => service.followUp(ctx, sessionId, payload));
64
- },
65
- async clearQueue(ctx, sessionId, payload) {
66
- await admit(ctx);
67
- return invokeObservedServiceEffect(() => service.clearQueue(ctx, sessionId, payload));
68
- },
69
- async interrupt(ctx, sessionId, payload) {
70
- await admit(ctx);
71
- return invokeObservedServiceEffect(() => service.interrupt(ctx, sessionId, payload));
72
- },
73
- async stop(ctx, sessionId, payload) {
74
- await admit(ctx);
75
- return invokeObservedServiceEffect(() => service.stop(ctx, sessionId, payload));
76
- },
77
- ...service.dispose ? { dispose: () => service.dispose() } : {}
78
- };
79
- }
80
-
81
- // src/core/createAgent.ts
82
- var DEFAULT_LIVE_BUFFER_SIZE = 1e3;
83
- function createAgent(config) {
84
- return createAgentRuntimeBridge(config).agent;
85
- }
86
- function createAgentRuntimeBridge(config) {
87
- const runtimeLoader = createRuntimeLoader(async () => {
88
- const runtime = await config.runtimeFactory();
89
- return config.admitEffect ? { ...runtime, service: withAgentEffectAdmission(runtime.service, config.admitEffect) } : runtime;
90
- });
91
- const live = new AgentLiveEventBuffer(DEFAULT_LIVE_BUFFER_SIZE);
92
- const sessionContexts = /* @__PURE__ */ new Map();
93
- const startedSessions = /* @__PURE__ */ new Map();
94
- const sendLocks = /* @__PURE__ */ new Map();
95
- const producerTeardownLocks = /* @__PURE__ */ new Map();
96
- let disposed = false;
97
- let disposePromise;
98
- const assertActive = () => {
99
- if (disposed) {
100
- throw stableAgentError(ErrorCode.enum.AGENT_BINDING_DISPOSED, "agent binding has been disposed");
101
- }
102
- };
103
- const getRuntime = async () => {
104
- assertActive();
105
- const runtime = await runtimeLoader.get();
106
- assertActive();
107
- return runtime;
108
- };
109
- const sessions = createFacadeSessionStore(
110
- getRuntime,
111
- assertActive,
112
- live,
113
- sessionContexts,
114
- startedSessions,
115
- runProducerTeardown
116
- );
117
- const readiness = createReadiness(config, assertActive);
118
- async function ensureSession(input, runtime) {
119
- if (input.sessionId) {
120
- const ctx = await authorizeSessionAccess(runtime, input.sessionId, input.ctx, sessionContexts);
121
- return { sessionId: input.sessionId, sessionKey: sessionCacheKey(input.sessionId, ctx), ctx };
122
- }
123
- const service = runtime.service;
124
- const created = await service.createSession(toPiRequestContext(input.ctx), {
125
- title: contentToText(input.content ?? input.message).slice(0, 80) || void 0
126
- });
127
- rememberSessionCtx(sessionContexts, created.id, input.ctx);
128
- return { sessionId: created.id, sessionKey: sessionCacheKey(created.id, input.ctx), ctx: input.ctx };
129
- }
130
- async function ensureBridge(sessionKey, sessionId, ctx, service) {
131
- const state = live.ensure(sessionKey);
132
- if (state.bridge || state.closed) return state;
133
- state.bridgePromise ??= (async () => {
134
- const subscribeFrom = state.latestIndex === 0 ? 0 : Number.MAX_SAFE_INTEGER;
135
- let result = await service.subscribe(toPiRequestContext(ctx), sessionId, subscribeFrom, (chunk) => {
136
- if (!state.closed) live.publish(sessionKey, sessionId, chunk);
137
- });
138
- if (result.type !== "ok") {
139
- result = await service.subscribe(toPiRequestContext(ctx), sessionId, result.latestSeq, (chunk) => {
140
- if (!state.closed) live.publish(sessionKey, sessionId, chunk);
141
- });
142
- }
143
- if (result.type !== "ok") throw new AgentNotImplementedError("Historical pi-chat replay is not implemented until T1.");
144
- if (disposed || state.closed) {
145
- result.unsubscribe();
146
- if (disposed) assertActive();
147
- throw stableAgentError(ErrorCode.enum.ABORTED, "session stopped while start was pending");
148
- }
149
- state.bridge = result;
150
- result.closed?.finally(() => live.close(sessionKey, state)).catch(() => live.close(sessionKey, state));
151
- return state;
152
- })();
153
- try {
154
- return await state.bridgePromise;
155
- } finally {
156
- state.bridgePromise = void 0;
157
- }
158
- }
159
- async function start(input) {
160
- assertActive();
161
- const runtime = await getRuntime();
162
- const { sessionId, sessionKey, ctx } = await ensureSession(input, runtime);
163
- assertActive();
164
- startedSessions.set(sessionKey, { sessionId, ctx });
165
- await ensureBridge(sessionKey, sessionId, ctx, runtime.service);
166
- assertActive();
167
- const startIndex = live.latestIndex(sessionKey);
168
- await runtime.service.prompt(toPiRequestContext(ctx), sessionId, toPromptPayload(input));
169
- assertActive();
170
- return { sessionId, startIndex };
171
- }
172
- const agent = {
173
- sessions,
174
- readiness,
175
- start,
176
- stream(sessionId, options) {
177
- assertActive();
178
- return authorizedStream(sessionId, options);
179
- },
180
- async *send(input) {
181
- assertActive();
182
- const release = input.sessionId ? await acquireSessionLock(sendLocks, sessionCacheKey(input.sessionId, input.ctx)) : void 0;
183
- try {
184
- assertActive();
185
- const receipt = await start(input);
186
- let turnId;
187
- for await (const event of authorizedStream(receipt.sessionId, { startIndex: receipt.startIndex, ctx: input.ctx })) {
188
- yield event;
189
- if (event.chunk.type === "agent-start") turnId = event.chunk.turnId;
190
- if (isSendTerminalEvent(event, turnId)) break;
191
- }
192
- } finally {
193
- release?.();
194
- }
195
- },
196
- async resolveInput(_sessionId, _requestId, _response) {
197
- assertActive();
198
- throw new AgentNotImplementedError("resolveInput is not implemented until T1.");
199
- },
200
- async interrupt(sessionId, ctx) {
201
- assertActive();
202
- const runtime = await getRuntime();
203
- const accessCtx = await authorizeSessionAccess(runtime, sessionId, ctx, sessionContexts);
204
- assertActive();
205
- return runtime.service.interrupt(toPiRequestContext(accessCtx), sessionId, {});
206
- },
207
- async stop(sessionId, ctx) {
208
- assertActive();
209
- const runtime = await getRuntime();
210
- const accessCtx = await authorizeSessionAccess(runtime, sessionId, ctx, sessionContexts);
211
- assertActive();
212
- const sessionKey = sessionCacheKey(sessionId, accessCtx);
213
- return runProducerTeardown(sessionKey, async () => {
214
- assertActive();
215
- const receipt = await runtime.service.stop(toPiRequestContext(accessCtx), sessionId, {});
216
- startedSessions.delete(sessionKey);
217
- live.close(sessionKey);
218
- return receipt;
219
- });
220
- },
221
- dispose() {
222
- disposed = true;
223
- disposePromise ??= disposeBinding();
224
- return disposePromise;
225
- }
226
- };
227
- async function disposeBinding() {
228
- const started = [...startedSessions.entries()];
229
- let runtime;
230
- let teardownError;
231
- try {
232
- runtime = await runtimeLoader.current();
233
- if (runtime) {
234
- const activeRuntime = runtime;
235
- const results = await Promise.allSettled(started.map(
236
- ([sessionKey, session]) => runProducerTeardown(sessionKey, async () => {
237
- if (startedSessions.get(sessionKey) !== session) return;
238
- await activeRuntime.service.stop(toPiRequestContext(session.ctx), session.sessionId, {});
239
- startedSessions.delete(sessionKey);
240
- live.close(sessionKey);
241
- })
242
- ));
243
- const failed = results.find((result) => result.status === "rejected");
244
- if (failed) throw failed.reason;
245
- }
246
- } catch (error) {
247
- teardownError = error;
248
- }
249
- try {
250
- await runtime?.service.dispose?.();
251
- } catch (error) {
252
- teardownError ??= error;
253
- } finally {
254
- try {
255
- live.dispose();
256
- } catch (error) {
257
- teardownError ??= error;
258
- } finally {
259
- startedSessions.clear();
260
- sessionContexts.clear();
261
- sendLocks.clear();
262
- producerTeardownLocks.clear();
263
- }
264
- }
265
- if (teardownError) throw teardownError;
266
- }
267
- async function runProducerTeardown(sessionKey, teardown) {
268
- const release = await acquireSessionLock(producerTeardownLocks, sessionKey);
269
- try {
270
- return await teardown();
271
- } finally {
272
- release();
273
- }
274
- }
275
- return {
276
- agent,
277
- getRuntime,
278
- currentRuntime() {
279
- assertActive();
280
- return runtimeLoader.current();
281
- }
282
- };
283
- async function* authorizedStream(sessionId, options) {
284
- assertActive();
285
- const runtime = await getRuntime();
286
- const accessCtx = await authorizeSessionAccess(runtime, sessionId, options.ctx, sessionContexts);
287
- assertActive();
288
- yield* live.stream(sessionCacheKey(sessionId, accessCtx), options.startIndex);
289
- }
290
- }
291
- function createRuntimeLoader(runtimeFactory) {
292
- let runtimePromise;
293
- return {
294
- get() {
295
- runtimePromise ??= Promise.resolve().then(() => runtimeFactory());
296
- return runtimePromise;
297
- },
298
- current() {
299
- return runtimePromise;
300
- }
301
- };
302
- }
303
- function createReadiness(config, assertActive) {
304
- const reporter = config.readiness;
305
- const requirements = [...reporter?.requirements ?? config.readinessRequirements ?? []];
306
- return {
307
- requirements,
308
- async status() {
309
- assertActive();
310
- if (!reporter) {
311
- return requirements.map((key) => ({
312
- key,
313
- ready: false,
314
- message: "readiness status is not available in the core facade"
315
- }));
316
- }
317
- const statuses = await reporter.status();
318
- assertActive();
319
- return statuses;
320
- }
321
- };
322
- }
323
- function createFacadeSessionStore(getRuntime, assertActive, live, sessionContexts, startedSessions, runProducerTeardown) {
324
- const store = async () => (await getRuntime()).sessionStore;
325
- return {
326
- async list(ctx, options) {
327
- assertActive();
328
- const summaries = await (await store()).list(ctx, options);
329
- assertActive();
330
- return summaries.filter((summary) => canAccessStoredSessionCtx(summary.id, ctx, sessionContexts));
331
- },
332
- async create(ctx, init) {
333
- assertActive();
334
- const runtime = await getRuntime();
335
- const created = await runtime.service.createSession(toPiRequestContext(ctx), init);
336
- assertActive();
337
- rememberSessionCtx(sessionContexts, created.id, ctx);
338
- return created;
339
- },
340
- async load(ctx, sessionId) {
341
- assertActive();
342
- const runtime = await getRuntime();
343
- const accessCtx = await authorizeSessionAccess(runtime, sessionId, ctx, sessionContexts);
344
- assertActive();
345
- const loaded = await (await store()).load(accessCtx ?? {}, sessionId);
346
- assertActive();
347
- return loaded;
348
- },
349
- async delete(ctx, sessionId) {
350
- assertActive();
351
- const runtime = await getRuntime();
352
- const accessCtx = await authorizeSessionAccess(runtime, sessionId, ctx, sessionContexts);
353
- assertActive();
354
- const sessionKey = sessionCacheKey(sessionId, accessCtx);
355
- await runProducerTeardown(sessionKey, async () => {
356
- assertActive();
357
- await runtime.service.deleteSession(toPiRequestContext(accessCtx), sessionId);
358
- startedSessions.delete(sessionKey);
359
- live.close(sessionKey);
360
- sessionContexts.delete(sessionKey);
361
- });
362
- }
363
- };
364
- }
365
- function toPiRequestContext(ctx) {
366
- return {
367
- workspaceId: ctx?.workspaceId,
368
- authSubject: ctx?.userId,
369
- requestId: "agent-core"
370
- };
371
- }
372
- function toPromptPayload(input) {
373
- return {
374
- message: contentToText(input.content ?? input.message),
375
- clientNonce: `agent:${Date.now()}:${Math.random().toString(36).slice(2)}`,
376
- ...input.model ? { model: input.model } : {},
377
- ...input.thinkingLevel ? { thinkingLevel: input.thinkingLevel } : {},
378
- ...input.attachments ? { attachments: input.attachments } : {}
379
- };
380
- }
381
- function contentToText(content) {
382
- if (content === void 0) return "";
383
- if (typeof content === "string") return content;
384
- return content.map((part) => part.text).filter((text) => typeof text === "string" && text.length > 0).join("\n");
385
- }
386
- async function loadSession(store, ctx, sessionId) {
387
- try {
388
- await store.load(ctx, sessionId);
389
- } catch (error) {
390
- throw normalizeSessionLoadError(error, sessionId);
391
- }
392
- }
393
- async function assertLoadedSessionVisible(store, ctx, sessionId) {
394
- const summaries = await store.list(ctx, { includeId: sessionId });
395
- if (!summaries.some((summary) => summary.id === sessionId)) {
396
- throw stableAgentError(ErrorCode.enum.UNAUTHORIZED, "session context mismatch");
397
- }
398
- }
399
- function normalizeSessionLoadError(error, sessionId) {
400
- if (error?.code === ErrorCode.enum.SESSION_NOT_FOUND || isPlainSessionNotFound(error, sessionId)) {
401
- return stableAgentError(ErrorCode.enum.SESSION_NOT_FOUND, "session not found");
402
- }
403
- return error;
404
- }
405
- async function authorizeSessionAccess(runtime, sessionId, callerCtx, sessionContexts) {
406
- const requestedKey = sessionCacheKey(sessionId, callerCtx);
407
- const hasStoredCtx = sessionContexts.has(requestedKey);
408
- const storedCtx = sessionContexts.get(requestedKey);
409
- if (hasStoredCtx && callerCtx && !sameSessionCtx(callerCtx, storedCtx)) {
410
- throw stableAgentError(ErrorCode.enum.UNAUTHORIZED, "session context mismatch");
411
- }
412
- if (hasStoredCtx && !callerCtx && !isEmptySessionCtx(storedCtx)) {
413
- throw stableAgentError(ErrorCode.enum.UNAUTHORIZED, "session context required");
414
- }
415
- const accessCtx = callerCtx ?? storedCtx ?? {};
416
- await loadSession(runtime.sessionStore, accessCtx, sessionId);
417
- if (!hasStoredCtx) {
418
- await assertLoadedSessionVisible(runtime.sessionStore, accessCtx, sessionId);
419
- rememberSessionCtx(sessionContexts, sessionId, accessCtx);
420
- }
421
- return accessCtx;
422
- }
423
- function rememberSessionCtx(sessionContexts, sessionId, ctx) {
424
- sessionContexts.set(sessionCacheKey(sessionId, ctx), isEmptySessionCtx(ctx) ? void 0 : { workspaceId: ctx?.workspaceId, userId: ctx?.userId });
425
- }
426
- function sameSessionCtx(a, b) {
427
- return (a?.workspaceId ?? "") === (b?.workspaceId ?? "") && (a?.userId ?? "") === (b?.userId ?? "");
428
- }
429
- function isEmptySessionCtx(ctx) {
430
- return !ctx?.workspaceId && !ctx?.userId;
431
- }
432
- function canAccessStoredSessionCtx(sessionId, callerCtx, sessionContexts) {
433
- const sessionKey = sessionCacheKey(sessionId, callerCtx);
434
- if (!sessionContexts.has(sessionKey)) return true;
435
- const storedCtx = sessionContexts.get(sessionKey);
436
- return sameSessionCtx(callerCtx, storedCtx);
437
- }
438
- function sessionCacheKey(sessionId, ctx) {
439
- return JSON.stringify([sessionId, ctx?.workspaceId ?? "", ctx?.userId ?? ""]);
440
- }
441
- function stableAgentError(code, message) {
442
- return Object.assign(new Error(message), { code });
443
- }
444
- async function acquireSessionLock(locks, sessionId) {
445
- const previous = locks.get(sessionId) ?? Promise.resolve();
446
- let release;
447
- const current = previous.catch(() => {
448
- }).then(() => new Promise((resolve) => {
449
- release = resolve;
450
- }));
451
- locks.set(sessionId, current);
452
- await previous.catch(() => {
453
- });
454
- return () => {
455
- release();
456
- if (locks.get(sessionId) === current) locks.delete(sessionId);
457
- };
458
- }
459
- function isPlainSessionNotFound(error, sessionId) {
460
- return error instanceof Error && (error.message === "session not found" || error.message === `Session not found: ${sessionId}` || error.message === `missing session ${sessionId}`);
461
- }
462
- function isSendTerminalEvent(event, turnId) {
463
- const chunk = event.chunk;
464
- if (chunk.type === "error") return !chunk.turnId || chunk.turnId === turnId;
465
- return chunk.type === "agent-end" && chunk.willRetry !== true && chunk.turnId === turnId;
466
- }
467
- var AgentLiveEventBuffer = class {
468
- constructor(maxEvents) {
469
- this.maxEvents = maxEvents;
470
- }
471
- maxEvents;
472
- sessions = /* @__PURE__ */ new Map();
473
- eventIndexes = /* @__PURE__ */ new Map();
474
- disposed = false;
475
- latestIndex(sessionKey) {
476
- return this.eventIndexes.get(sessionKey) ?? 0;
477
- }
478
- ensure(sessionKey) {
479
- let state = this.sessions.get(sessionKey);
480
- if (!state || state.closed) {
481
- const latestIndex = this.latestIndex(sessionKey);
482
- state = {
483
- events: [],
484
- subscribers: /* @__PURE__ */ new Set(),
485
- latestIndex,
486
- evictedThroughIndex: latestIndex - 1,
487
- closed: false
488
- };
489
- this.sessions.set(sessionKey, state);
490
- }
491
- return state;
492
- }
493
- publish(sessionKey, sessionId, chunk) {
494
- if (this.disposed) return;
495
- const state = this.ensure(sessionKey);
496
- if (state.closed) return;
497
- const eventIndex = this.latestIndex(sessionKey);
498
- this.eventIndexes.set(sessionKey, eventIndex + 1);
499
- const event = {
500
- v: 1,
501
- eventIndex,
502
- timestamp: Date.now(),
503
- sessionId,
504
- chunk
505
- };
506
- state.latestIndex = event.eventIndex + 1;
507
- state.events.push(event);
508
- if (state.events.length > this.maxEvents) {
509
- const evicted = state.events.splice(0, state.events.length - this.maxEvents);
510
- state.evictedThroughIndex = evicted[evicted.length - 1]?.eventIndex ?? state.evictedThroughIndex;
511
- }
512
- for (const subscriber of state.subscribers) subscriber.push(event);
513
- }
514
- stream(sessionKey, startIndex) {
515
- const state = this.ensure(sessionKey);
516
- this.assertReplayable(state, startIndex);
517
- return {
518
- [Symbol.asyncIterator]: () => {
519
- this.assertReplayable(state, startIndex);
520
- return createLiveIterator(state, startIndex);
521
- }
522
- };
523
- }
524
- close(sessionKey, expectedState) {
525
- const state = this.sessions.get(sessionKey);
526
- if (!state || expectedState && state !== expectedState) return;
527
- state.closed = true;
528
- let unsubscribeError;
529
- try {
530
- state.bridge?.unsubscribe();
531
- } catch (error) {
532
- unsubscribeError = error;
533
- }
534
- for (const subscriber of state.subscribers) subscriber.close();
535
- state.subscribers.clear();
536
- if (unsubscribeError) throw unsubscribeError;
537
- }
538
- dispose() {
539
- if (this.disposed) return;
540
- this.disposed = true;
541
- let disposeError;
542
- for (const [sessionId] of this.sessions) {
543
- try {
544
- this.close(sessionId);
545
- } catch (error) {
546
- disposeError ??= error;
547
- }
548
- }
549
- this.sessions.clear();
550
- this.eventIndexes.clear();
551
- if (disposeError) throw disposeError;
552
- }
553
- assertReplayable(state, startIndex) {
554
- if (!Number.isInteger(startIndex) || startIndex < 0) {
555
- throw cursorOutOfRangeError("startIndex must be a non-negative integer", {
556
- startIndex,
557
- latestIndex: state.latestIndex
558
- });
559
- }
560
- if (startIndex <= state.evictedThroughIndex) {
561
- throw new AgentNotImplementedError("Historical stream replay is not implemented until T1.");
562
- }
563
- if (startIndex > state.latestIndex) {
564
- throw cursorOutOfRangeError(`startIndex ${startIndex} is ahead of next eventIndex ${state.latestIndex}`, {
565
- startIndex,
566
- latestIndex: state.latestIndex
567
- });
568
- }
569
- }
570
- };
571
- function cursorOutOfRangeError(message, details) {
572
- return Object.assign(new RangeError(message), {
573
- code: ErrorCode.enum.CURSOR_OUT_OF_RANGE,
574
- details
575
- });
576
- }
577
- function createLiveIterator(state, startIndex) {
578
- const queued = [];
579
- const waiters = [];
580
- let active = true;
581
- const subscriber = {
582
- push(event) {
583
- if (!active) return;
584
- const waiter = waiters.shift();
585
- if (waiter) waiter({ value: event, done: false });
586
- else queued.push(event);
587
- },
588
- close() {
589
- if (!active) return;
590
- active = false;
591
- while (waiters.length > 0) waiters.shift()?.({ value: void 0, done: true });
592
- }
593
- };
594
- state.subscribers.add(subscriber);
595
- queued.push(...state.events.filter((event) => event.eventIndex >= startIndex));
596
- return {
597
- async next() {
598
- if (queued.length > 0) return { value: queued.shift(), done: false };
599
- if (!active || state.closed) return { value: void 0, done: true };
600
- return new Promise((resolve) => waiters.push(resolve));
601
- },
602
- async return() {
603
- active = false;
604
- state.subscribers.delete(subscriber);
605
- while (waiters.length > 0) waiters.shift()?.({ value: void 0, done: true });
606
- return { value: void 0, done: true };
607
- }
608
- };
609
- }
610
- export {
611
- AGENT_EFFECT_METHODS,
612
- AGENT_NOT_IMPLEMENTED_UNTIL_T1,
613
- AgentEffectAdmissionError,
614
- AgentNotImplementedError,
615
- createAgent,
616
- withAgentEffectAdmission
617
- };
@@ -1,18 +0,0 @@
1
- import {
2
- createPiCodingAgentHarness,
3
- createResourceSettingsManager,
4
- deriveSourcePlugin,
5
- mergePiPackageSources,
6
- projectSkillResourceLocations,
7
- withPiHarnessDefaults
8
- } from "./chunk-42D6KAQV.js";
9
- import "./chunk-7XAOVFSN.js";
10
- import "./chunk-KJIEMSQP.js";
11
- export {
12
- createPiCodingAgentHarness,
13
- createResourceSettingsManager,
14
- deriveSourcePlugin,
15
- mergePiPackageSources,
16
- projectSkillResourceLocations,
17
- withPiHarnessDefaults
18
- };