@agimon-ai/po-session 0.0.0-alpha.169 → 0.0.0-alpha.170

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.
@@ -13,6 +13,7 @@ let node_path = require("node:path");
13
13
  node_path = require_type.__toESM(node_path, 1);
14
14
  let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
15
15
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
16
+ let _agimon_ai_po_approval = require("@agimon-ai/po-approval");
16
17
  let _agimon_ai_po_core_contextContributions = require("@agimon-ai/po-core/contextContributions");
17
18
  let _agimon_ai_po_core_remoteOrigin = require("@agimon-ai/po-core/remoteOrigin");
18
19
  let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
@@ -76,6 +77,223 @@ var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)((pl
76
77
  });
77
78
  }]
78
79
  }));
80
+ const MAX_AGENT_RUN_TIMEOUT_MS = 72e5;
81
+ const POLL_MS = 1e3;
82
+ const NAME_MAX = 60;
83
+ const INPUT_KEYS = /* @__PURE__ */ new Set([
84
+ "task",
85
+ "systemPrompt",
86
+ "preset",
87
+ "modes",
88
+ "profile",
89
+ "domains",
90
+ "model",
91
+ "thinking",
92
+ "cwd",
93
+ "timeoutMs"
94
+ ]);
95
+ const LAST_CONTROL_CODE = 31;
96
+ const DELETE_CODE = 127;
97
+ function hasControl(text) {
98
+ for (let index = 0; index < text.length; index += 1) {
99
+ const code = text.charCodeAt(index);
100
+ if (code <= LAST_CONTROL_CODE || code === DELETE_CODE) return true;
101
+ }
102
+ return false;
103
+ }
104
+ /** A turn ended by these never produced a reply the caller can use. */
105
+ const UNFINISHED_STOPS = /* @__PURE__ */ new Set([
106
+ "error",
107
+ "aborted",
108
+ "toolUse"
109
+ ]);
110
+ /** A value that becomes a harness flag argument on Node: no leading dash, no control characters, bounded. */
111
+ function name(field, value, list = false) {
112
+ if (typeof value !== "string") throw new TypeError(`agent: ${field} must be a string.`);
113
+ const text = value.trim();
114
+ if (text === "" || text.length > _agimon_ai_po_core_hubChannel.MAX_LAUNCH_PROFILE_NAME_LENGTH || text.startsWith("-") || hasControl(text) || list && text.includes(",")) throw new TypeError(`agent: ${field} '${value.slice(0, 40)}' is not a valid name.`);
115
+ return text;
116
+ }
117
+ function names(field, value) {
118
+ if (!Array.isArray(value)) throw new TypeError(`agent: ${field} must be an array of names.`);
119
+ return [...new Set(value.map((entry) => name(field, entry, true)))];
120
+ }
121
+ /** Validates an agent run request at the trust boundary. Throws a TypeError naming the bad field. */
122
+ function parseAgentRunInput(value) {
123
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("agent: input must be an object with a task.");
124
+ const record = value;
125
+ for (const key of Object.keys(record)) {
126
+ if (key === "majorMode" || key === "minorModes") throw new TypeError(`agent: '${key}' is retired; use modes.`);
127
+ if (!INPUT_KEYS.has(key)) throw new TypeError(`agent: unknown field '${key}'.`);
128
+ }
129
+ const { task, systemPrompt, cwd, timeoutMs, profile } = record;
130
+ if (typeof task !== "string" || task.trim() === "") throw new TypeError("agent: task must be a non-empty string.");
131
+ if (systemPrompt !== void 0 && typeof systemPrompt !== "string") throw new TypeError("agent: systemPrompt must be a string.");
132
+ if (cwd !== void 0 && (typeof cwd !== "string" || !cwd.startsWith("/") || hasControl(cwd))) throw new TypeError("agent: cwd must be an absolute path.");
133
+ if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 72e5)) throw new TypeError(`agent: timeoutMs must be an integer from 1 to ${MAX_AGENT_RUN_TIMEOUT_MS}.`);
134
+ return {
135
+ task,
136
+ ...systemPrompt === void 0 || systemPrompt === "" ? {} : { systemPrompt },
137
+ ...record.preset === void 0 ? {} : { preset: name("preset", record.preset) },
138
+ ...record.modes === void 0 ? {} : { modes: names("modes", record.modes) },
139
+ ...profile === void 0 ? {} : { profile: profile === null ? null : name("profile", profile) },
140
+ ...record.domains === void 0 ? {} : { domains: names("domains", record.domains) },
141
+ ...record.model === void 0 ? {} : { model: name("model", record.model) },
142
+ ...record.thinking === void 0 ? {} : { thinking: name("thinking", record.thinking) },
143
+ ...cwd === void 0 ? {} : { cwd },
144
+ timeoutMs: timeoutMs ?? 6e5
145
+ };
146
+ }
147
+ /** Same request, same hash: the parsed input with its keys in a fixed order, so `profile: null` and unset differ. */
148
+ async function agentRunHash(input) {
149
+ const ordered = Object.fromEntries([...INPUT_KEYS].filter((key) => key in input).map((key) => [key, input[key]]));
150
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(ordered)));
151
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
152
+ }
153
+ /** Over message entries newest first, the newest assistant message decides: a finished reply, an error or abort, or nothing usable. */
154
+ function finalReply(entries) {
155
+ for (const item of entries) {
156
+ const entry = item;
157
+ const message = entry?.type === "message" ? entry.message : void 0;
158
+ if (message?.role !== "assistant") continue;
159
+ const stop = typeof message.stopReason === "string" ? message.stopReason : "";
160
+ if (stop === "error") return {
161
+ status: "failed",
162
+ error: typeof message.errorMessage === "string" ? message.errorMessage : "The agent run failed."
163
+ };
164
+ if (stop === "aborted") return {
165
+ status: "stopped",
166
+ error: "The agent run was stopped."
167
+ };
168
+ if (UNFINISHED_STOPS.has(stop)) return void 0;
169
+ const content = message.content;
170
+ const text = (typeof content === "string" ? content : Array.isArray(content) ? content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join("") : "").trim();
171
+ return text === "" ? void 0 : {
172
+ status: "completed",
173
+ text
174
+ };
175
+ }
176
+ }
177
+ function selectionOf(input) {
178
+ const selection = {
179
+ ...input.preset === void 0 ? {} : { preset: input.preset },
180
+ ...input.modes === void 0 ? {} : { modes: input.modes },
181
+ ...input.profile === void 0 ? {} : { profile: input.profile },
182
+ ...input.domains === void 0 ? {} : { domains: input.domains }
183
+ };
184
+ return Object.keys(selection).length === 0 ? void 0 : selection;
185
+ }
186
+ function errorText(error) {
187
+ return error instanceof Error ? error.message : String(error);
188
+ }
189
+ /** Settles with `work`, or rejects once `signal` aborts; no timer or listener outlives it. */
190
+ function until(work, signal) {
191
+ if (signal.aborted) return Promise.reject(signal.reason);
192
+ let stop = () => void 0;
193
+ const aborted = new Promise((_resolve, reject) => {
194
+ stop = () => reject(signal.reason);
195
+ signal.addEventListener("abort", stop, { once: true });
196
+ });
197
+ return Promise.race([work, aborted]).finally(() => signal.removeEventListener("abort", stop));
198
+ }
199
+ function pause(ms, signal) {
200
+ let timer;
201
+ return until(new Promise((resolve) => {
202
+ timer = setTimeout(resolve, ms);
203
+ }), signal).finally(() => clearTimeout(timer));
204
+ }
205
+ /**
206
+ * Runs tasks in unattended child sessions of one owning session. A child keeps the workflow-step provenance, so it
207
+ * stays out of the rail and reads like a step session once released.
208
+ */
209
+ function createAgentRunService(dependencies) {
210
+ const { sessionId: parentSessionId, sessions } = dependencies;
211
+ const pollMs = dependencies.pollMs ?? POLL_MS;
212
+ return { async run(raw, options = {}) {
213
+ const input = parseAgentRunInput(raw);
214
+ const hash = await agentRunHash(input);
215
+ const cwd = input.cwd ?? dependencies.cwd;
216
+ if (!sessions?.prompt || !sessions.readExecutionState || !sessions.readMessages || cwd === void 0) return {
217
+ status: "failed",
218
+ output: "",
219
+ error: "This host cannot run agent sessions."
220
+ };
221
+ const timeout = AbortSignal.timeout(input.timeoutMs);
222
+ const signal = AbortSignal.any([
223
+ dependencies.lifetime,
224
+ timeout,
225
+ ...options.signal === void 0 ? [] : [options.signal]
226
+ ]);
227
+ const owned = { parentSessionId };
228
+ let sessionId;
229
+ let result;
230
+ try {
231
+ const selection = selectionOf(input);
232
+ sessionId = (await sessions.create({
233
+ cwd,
234
+ name: `Agent: ${input.task.trim().split("\n", 1)[0].slice(0, NAME_MAX)}`,
235
+ parentSessionId,
236
+ sessionProvenance: _agimon_ai_po_core_hubChannel.WORKFLOW_STEP_SESSION_PROVENANCE,
237
+ interaction: "unattended",
238
+ ...selection === void 0 ? {} : { selection },
239
+ ...input.model === void 0 ? {} : { model: input.model },
240
+ ...input.thinking === void 0 ? {} : { thinking: input.thinking },
241
+ ...input.systemPrompt === void 0 ? {} : { appendSystemPrompt: input.systemPrompt },
242
+ signal
243
+ })).sessionId;
244
+ options.onStarted?.(sessionId, hash);
245
+ await until((await sessions.prompt(sessionId, input.task, {
246
+ ...owned,
247
+ signal
248
+ })).settled, signal);
249
+ for (;;) {
250
+ const state = await sessions.readExecutionState(sessionId, owned);
251
+ if (state.isIdle && !state.hasPendingMessages && !(state.backgroundWork?.items.some(_agimon_ai_po_core_backgroundWork.holdsSettledSession) ?? false) && ((await dependencies.approvals()?.unsettled(sessionId))?.length ?? 0) === 0) break;
252
+ await pause(pollMs, signal);
253
+ }
254
+ const reply = finalReply(await sessions.readMessages(sessionId, {
255
+ ...owned,
256
+ limit: 20
257
+ }));
258
+ result = reply === void 0 ? {
259
+ sessionId,
260
+ status: "failed",
261
+ output: "",
262
+ error: "The agent ended without a reply."
263
+ } : reply.status === "completed" ? {
264
+ sessionId,
265
+ status: "completed",
266
+ output: reply.text
267
+ } : {
268
+ sessionId,
269
+ status: reply.status,
270
+ output: "",
271
+ error: reply.error
272
+ };
273
+ } catch (error) {
274
+ result = {
275
+ ...sessionId === void 0 ? {} : { sessionId },
276
+ status: signal.aborted && !timeout.aborted ? "stopped" : "failed",
277
+ output: "",
278
+ error: timeout.aborted ? `The agent did not finish within ${input.timeoutMs}ms.` : errorText(error)
279
+ };
280
+ }
281
+ if (sessionId !== void 0) {
282
+ const child = sessionId;
283
+ const cleanup = async (step) => {
284
+ try {
285
+ await step();
286
+ } catch (error) {
287
+ dependencies.onError?.(error);
288
+ }
289
+ };
290
+ if (signal.aborted) await cleanup(() => sessions.abort?.(child, owned));
291
+ await cleanup(() => dependencies.approvals()?.abandon(child));
292
+ await cleanup(() => sessions.release?.(child, owned));
293
+ }
294
+ return result;
295
+ } };
296
+ }
79
297
  //#endregion
80
298
  //#region src/services/networkNamespace/index.ts
81
299
  /** `{ to, text, urgent? }`, validated at the namespace boundary. `urgent` exists only where the host has lanes. */
@@ -477,10 +695,34 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plug
477
695
  await closeDelivery();
478
696
  };
479
697
  });
698
+ },
699
+ (owner) => {
700
+ const sessionId = pluginContext.host.context.sessionId;
701
+ if (sessionId === void 0) return;
702
+ const lifetime = new AbortController();
703
+ const binding = owner.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE], async (context) => {
704
+ const scope = (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(context);
705
+ const service = createAgentRunService({
706
+ sessionId,
707
+ cwd: pluginContext.host.context.cwd,
708
+ sessions: pluginContext.host.context.sessionService,
709
+ approvals: () => scope.resolve(_agimon_ai_po_approval.APPROVAL_ROOT_SERVICE),
710
+ lifetime: lifetime.signal,
711
+ onError: (error) => pluginContext.host.context.onNotice(`Agent run cleanup failed: ${String(error)}`)
712
+ });
713
+ return await scope.provide(_agimon_ai_po_core_hubChannel.PO_AGENT_RUN_CONTRACT, service);
714
+ });
715
+ return async () => {
716
+ lifetime.abort(/* @__PURE__ */ new Error("The session that started this agent run closed."));
717
+ await binding.dispose();
718
+ };
480
719
  }
481
720
  ]
482
721
  }));
483
722
  //#endregion
723
+ //#region src/extensions/workspaces/sessions/(backend)/contract/agentRun.server.ts
724
+ var agentRun_server_default = (0, _agimon_ai_po_core_extensionFile.defineServiceContract)(_agimon_ai_po_core_hubChannel.PO_AGENT_RUN_CONTRACT.name, _agimon_ai_po_core_hubChannel.PO_AGENT_RUN_CONTRACT);
725
+ //#endregion
484
726
  //#region src/services/peerInboxApi/index.ts
485
727
  const MAX_BODY_BYTES = 65536;
486
728
  const DELIVERY_TYPES = /* @__PURE__ */ new Set(["po/session-delivery/envelope", "po/session-delivery/ack"]);
@@ -780,6 +1022,7 @@ const defined = (values) => values.filter((value) => value !== void 0);
780
1022
  const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
781
1023
  name: "@agimon-ai/po-session",
782
1024
  providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default$1, root_server_default),
1025
+ provides: { session: [agentRun_server_default] },
783
1026
  injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({
784
1027
  host: [root_server_default$1],
785
1028
  workspace: [root_server_default$1],