@agimon-ai/po-session 0.0.0-alpha.21 → 0.0.0-alpha.211
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/LICENSE +21 -149
- package/README.md +47 -1
- package/dist/apiContracts.cjs +34 -2
- package/dist/apiContracts.cjs.map +1 -1
- package/dist/apiContracts.d.mts +2 -2
- package/dist/apiContracts.d.mts.map +1 -1
- package/dist/apiContracts.mjs +35 -2
- package/dist/apiContracts.mjs.map +1 -1
- package/dist/extensions/native.mjs +410 -0
- package/dist/extensions/native.mjs.map +1 -0
- package/dist/extensions/server.cjs +1661 -113
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.d.mts.map +1 -1
- package/dist/extensions/server.mjs +1657 -109
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +361 -0
- package/dist/extensions/web.mjs.map +1 -0
- package/dist/index.cjs +410 -25
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.mts +599 -82
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +358 -1
- package/dist/index.mjs.map +1 -0
- package/dist/po-runtime-identity.json +1 -0
- package/dist/type-BlbiS10p.mjs +2622 -0
- package/dist/type-BlbiS10p.mjs.map +1 -0
- package/dist/type-DZtqhE4a.cjs +3083 -0
- package/dist/type-DZtqhE4a.cjs.map +1 -0
- package/llms.txt +4 -1
- package/locales/vi.json +29 -0
- package/locales/zh-CN.json +29 -0
- package/package.json +96 -11
- package/src/prompts/codemode-how-to-network/SKILL.md +49 -0
- package/src/prompts/codemode-how-to-session/SKILL.md +25 -0
- package/dist/sessionDelivery-4svjzWUW.mjs +0 -1028
- package/dist/sessionDelivery-4svjzWUW.mjs.map +0 -1
- package/dist/sessionDelivery-CGWuQyLV.cjs +0 -1219
- package/dist/sessionDelivery-CGWuQyLV.cjs.map +0 -1
|
@@ -1,9 +1,916 @@
|
|
|
1
|
-
import { D as
|
|
1
|
+
import { $ as createLogbookWake, A as createPeerReplayGuardAsync, B as authenticatedPeerPost, C as undeliveredNotice, D as namedSessionGroupId, E as createSessionGroupBridge, F as peerSessionReference, G as provideSessionDeliveryService, H as PEER_REPLAY_DATABASE_FILE, I as readSessionPeerConfigAsync, J as INBOX_DIGEST_DELAY_MS, L as verifyPeerRequest, M as parseRemoteSessionReference, N as parseSessionPeerEnvelope, O as readSessionGroupBridge, P as peerRequestHeaders, Q as createInboxDigest, T as PO_SESSION_GROUP_BRIDGE_SERVICE, U as sessionPeerConfigPath, V as createSealedPeerChannels, X as STOP_LEVEL, Y as LOGBOOK_WAKE_DELAY_MS, Z as STOP_REPORT_DELAY_MS, _ as INTERCOM_MESSAGE_TYPE, a as PO_SESSION_PEERS_SERVICE, at as parseMarkReadInput, b as intercomDetails, c as requireSessionPeers, ct as fields, d as PO_SESSION_INTERCOM_SERVICE, dt as START_SESSION_TOOL_NAME, et as createStopReport, ft as createStartSessionTool, g as createSessionDirectory, i as PO_SESSION_PEERS_CONTRACT, it as parseLogbookQuery, j as ensurePrivateDirectory, k as createPeerCommunication, l as createSessionGroupDeliveryAuthorizer, m as createSessionGroupStore, n as PO_ROSTER_PEER_SERVICE, nt as oneLine, o as createSessionPeers, ot as createSessionsNamespace, q as readPoSessionDelivery, r as createPeerLink, rt as parseLogInput, st as detach, tt as lastAssistantText, u as createSessionIntercom, ut as readSessionOperations, vt as provideBackgroundWorkService, w as PO_SESSION_GROUP_BRIDGE_CONTRACT, x as rearmAskReminders, y as createNodeSessionOperations } from "../type-BlbiS10p.mjs";
|
|
2
|
+
import { PO_BACKGROUND_WORK_SERVICE, awaitsCompletion, holdsSettledSession, readPoBackgroundWorkService } from "@agimon-ai/po-core/backgroundWork";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { COORDINATOR_SESSION_PROVENANCE, MAX_LAUNCH_PROFILE_NAME_LENGTH, PO_AGENT_RUN_CONTRACT, PO_CHILD_REPORT_CONTRACT, PO_CHILD_REPORT_STEER_TYPE, PO_CHILD_REPORT_TYPE, PO_CHILD_REPORT_WORK_PROVIDER, PO_SESSION_ATTENTION_EVENT, WORKFLOW_STEP_SESSION_PROVENANCE, reportsToParent } from "@agimon-ai/po-core/hubChannel";
|
|
5
|
+
import { PO_CODEMODE_SERVICE, assertCodemodeNamespaceName, readPoCodemode } from "@agimon-ai/po-core/codemode";
|
|
6
|
+
import { composeRootHooks, composeRootInjects, defineHook, defineResource, defineRoot, defineRoute, defineRoutedContribution, defineServiceContract } from "@agimon-ai/po-core/extensionFile";
|
|
7
|
+
import { BACKGROUND_CONTEXT, PO_FS_SERVICE, PO_SQLITE_SERVICE, requirePoFs, requirePoSqlite } from "@agimon-ai/po-core/platform";
|
|
2
8
|
import path from "node:path";
|
|
3
|
-
import { BACKGROUND_CONTEXT, requirePoFs, requirePoSqlite } from "@agimon-ai/po-core/platform";
|
|
4
9
|
import { poHomeDirectory } from "@agimon-ai/po-core/piSettings";
|
|
5
|
-
import { composeServerProviderOverrides, defineServerPlugin } from "@agimon-ai/po-core/serverPlugin";
|
|
6
|
-
import {
|
|
10
|
+
import { PO_SERVER_SCOPE_SERVICE, composeServerProviderOverrides, defineServerMethod, defineServerPlugin, packageResourcePath, readPackageResource, requirePoServerScope } from "@agimon-ai/po-core/serverPlugin";
|
|
11
|
+
import { APPROVAL_ROOT_SERVICE } from "@agimon-ai/po-approval";
|
|
12
|
+
import { readPoContextContributions } from "@agimon-ai/po-core/contextContributions";
|
|
13
|
+
import { formatMessage, readPoLang, readPoPersonLocale } from "@agimon-ai/po-core/locale";
|
|
14
|
+
import { PO_REMOTE_ORIGIN_SERVICE } from "@agimon-ai/po-core/remoteOrigin";
|
|
15
|
+
import { poApiCallerFrom } from "@agimon-ai/po-core/packageApi";
|
|
16
|
+
import { definePoPluginMethod } from "@agimon-ai/po-core/pluginProtocol";
|
|
17
|
+
//#region src/services/childReportLedger/index.ts
|
|
18
|
+
const SCHEMA = `
|
|
19
|
+
CREATE TABLE IF NOT EXISTS child_reports (
|
|
20
|
+
report_key TEXT PRIMARY KEY,
|
|
21
|
+
child_session_id TEXT,
|
|
22
|
+
episode INTEGER,
|
|
23
|
+
parent_session_id TEXT NOT NULL,
|
|
24
|
+
workspace_id TEXT NOT NULL,
|
|
25
|
+
state TEXT NOT NULL,
|
|
26
|
+
steers INTEGER NOT NULL DEFAULT 0,
|
|
27
|
+
outcome TEXT,
|
|
28
|
+
text TEXT,
|
|
29
|
+
summary TEXT,
|
|
30
|
+
context_json TEXT,
|
|
31
|
+
revived_parent INTEGER NOT NULL DEFAULT 0,
|
|
32
|
+
admit_failures INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
reported_at INTEGER,
|
|
34
|
+
updated_at INTEGER NOT NULL
|
|
35
|
+
);
|
|
36
|
+
CREATE INDEX IF NOT EXISTS child_reports_child ON child_reports(child_session_id, episode);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS child_reports_parent ON child_reports(parent_session_id, state);
|
|
38
|
+
`;
|
|
39
|
+
const TEXT_MAX = 4e3;
|
|
40
|
+
const LINE_MAX = 300;
|
|
41
|
+
const ADMIT_ATTEMPTS = 3;
|
|
42
|
+
const OUTCOMES = /* @__PURE__ */ new Set([
|
|
43
|
+
"done",
|
|
44
|
+
"blocked",
|
|
45
|
+
"failed",
|
|
46
|
+
"cancelled",
|
|
47
|
+
"interrupted"
|
|
48
|
+
]);
|
|
49
|
+
function episodeKey(childSessionId, episode) {
|
|
50
|
+
return `episode:${childSessionId}:${episode}`;
|
|
51
|
+
}
|
|
52
|
+
function toEpisode(row) {
|
|
53
|
+
return row?.episode == null ? void 0 : {
|
|
54
|
+
episode: Number(row.episode),
|
|
55
|
+
state: row.state,
|
|
56
|
+
steers: Number(row.steers)
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** Bounded, one-line context fields. Unknown keys are dropped so a source cannot smuggle prompts in. */
|
|
60
|
+
function boundContext(context) {
|
|
61
|
+
const bounded = {};
|
|
62
|
+
for (const key of [
|
|
63
|
+
"source",
|
|
64
|
+
"title",
|
|
65
|
+
"eventId",
|
|
66
|
+
"occurrenceId",
|
|
67
|
+
"runKey",
|
|
68
|
+
"runId",
|
|
69
|
+
"failedJob",
|
|
70
|
+
"errorClass",
|
|
71
|
+
"error"
|
|
72
|
+
]) if (typeof context?.[key] === "string") {
|
|
73
|
+
const value = oneLine(context[key], LINE_MAX);
|
|
74
|
+
if (value) bounded[key] = value;
|
|
75
|
+
}
|
|
76
|
+
return bounded;
|
|
77
|
+
}
|
|
78
|
+
function readContext(row) {
|
|
79
|
+
try {
|
|
80
|
+
return row.context_json ? JSON.parse(row.context_json) : {};
|
|
81
|
+
} catch {
|
|
82
|
+
return {};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function describeContext(context) {
|
|
86
|
+
const parts = [
|
|
87
|
+
context.source && context.title ? `${context.source} "${context.title}"` : context.source ?? context.title,
|
|
88
|
+
context.eventId && `event ${context.eventId}`,
|
|
89
|
+
context.runKey && `run ${context.runKey}${context.runId ? `/${context.runId}` : ""}`,
|
|
90
|
+
context.failedJob && `failed job ${context.failedJob}`,
|
|
91
|
+
context.errorClass && `error class ${context.errorClass}`,
|
|
92
|
+
context.error && `error: ${context.error}`
|
|
93
|
+
].filter(Boolean);
|
|
94
|
+
return parts.length ? parts.join(", ") : void 0;
|
|
95
|
+
}
|
|
96
|
+
/** Host-scope ledger: one terminal report per child episode, delivered once to a revived-if-needed parent. */
|
|
97
|
+
async function createChildReportLedger(options) {
|
|
98
|
+
const { database, sessions, onNotice } = options;
|
|
99
|
+
const now = options.now ?? Date.now;
|
|
100
|
+
await database.exec(SCHEMA);
|
|
101
|
+
const sinks = /* @__PURE__ */ new Map();
|
|
102
|
+
const delivering = /* @__PURE__ */ new Map();
|
|
103
|
+
const staleOpen = /* @__PURE__ */ new Set();
|
|
104
|
+
let closed = false;
|
|
105
|
+
const findSession = (sessionId) => sessions.scopes?.().find((entry) => entry.sessionId === sessionId) ?? sessions.dormant?.().find((entry) => entry.sessionId === sessionId);
|
|
106
|
+
const latestEpisode = (childSessionId) => database.get("SELECT * FROM child_reports WHERE child_session_id = ? AND episode IS NOT NULL ORDER BY episode DESC LIMIT 1", childSessionId);
|
|
107
|
+
const markReported = async (row, outcome, text, extra) => {
|
|
108
|
+
const context = {
|
|
109
|
+
...readContext(row),
|
|
110
|
+
...boundContext(extra)
|
|
111
|
+
};
|
|
112
|
+
await database.run("UPDATE child_reports SET state = 'reported', outcome = ?, text = ?, context_json = ?, reported_at = ?, updated_at = ? WHERE report_key = ?", extra?.errorClass && row.outcome ? row.outcome : outcome, text.trim().slice(0, TEXT_MAX), JSON.stringify(context), now(), now(), row.report_key);
|
|
113
|
+
};
|
|
114
|
+
const setState = (keys, state) => Promise.all(keys.map((key) => database.run("UPDATE child_reports SET state = ?, revived_parent = 0, updated_at = ? WHERE report_key = ?", state, now(), key)));
|
|
115
|
+
const render = (rows) => rows.map((row) => {
|
|
116
|
+
const child = row.child_session_id ? findSession(row.child_session_id) : void 0;
|
|
117
|
+
const lines = [`${row.child_session_id ? `Child session ${child?.name ? `"${oneLine(child.name, 80)}" ` : ""}(${row.child_session_id})` : "A run you started"} ended: ${row.outcome ?? "interrupted"}.`];
|
|
118
|
+
if (row.text) lines.push(`Report: ${row.text}`);
|
|
119
|
+
if (row.summary) lines.push(row.summary);
|
|
120
|
+
const context = describeContext(readContext(row));
|
|
121
|
+
if (context) lines.push(`Context: ${context}`);
|
|
122
|
+
return lines.join("\n");
|
|
123
|
+
}).concat("Resolve any blocker it reports, or continue the work. To give the child more work, message it with network.send.").join("\n\n");
|
|
124
|
+
const deliverParent = async (parentSessionId) => {
|
|
125
|
+
const rows = await database.all("SELECT * FROM child_reports WHERE parent_session_id = ? AND state = 'reported' ORDER BY reported_at, rowid", parentSessionId);
|
|
126
|
+
if (!rows.length || closed) return;
|
|
127
|
+
const keys = rows.map((row) => row.report_key);
|
|
128
|
+
const workspaceId = rows[0].workspace_id;
|
|
129
|
+
const parent = findSession(parentSessionId);
|
|
130
|
+
if (!parent || parent.workspaceId && parent.workspaceId !== workspaceId) {
|
|
131
|
+
if (!parent && !sessions.directoryReady?.(workspaceId)) return;
|
|
132
|
+
await setState(keys, "unavailable");
|
|
133
|
+
onNotice(`A child session report could not reach its parent session ${parentSessionId}: it no longer exists.`);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
let revived = rows.some((row) => row.revived_parent === 1);
|
|
137
|
+
if (!sessions.isLive(parentSessionId)) {
|
|
138
|
+
if (revived || !sessions.revive) return;
|
|
139
|
+
const result = await sessions.revive(parentSessionId, { automatic: true });
|
|
140
|
+
if (result === "not_found") {
|
|
141
|
+
await setState(keys, "unavailable");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (result !== "revived") return;
|
|
145
|
+
revived = true;
|
|
146
|
+
for (const key of keys) await database.run("UPDATE child_reports SET revived_parent = 1 WHERE report_key = ?", key);
|
|
147
|
+
}
|
|
148
|
+
const sink = sinks.get(parentSessionId);
|
|
149
|
+
if (!sink || sink.workspaceId !== workspaceId) return;
|
|
150
|
+
let receipt;
|
|
151
|
+
try {
|
|
152
|
+
receipt = await sink.sink.admit({
|
|
153
|
+
type: PO_CHILD_REPORT_TYPE,
|
|
154
|
+
text: render(rows),
|
|
155
|
+
display: true,
|
|
156
|
+
details: {
|
|
157
|
+
notice: oneLine(`Child report · ${rows.map((row) => {
|
|
158
|
+
return `${(row.child_session_id ? findSession(row.child_session_id) : void 0)?.name ?? row.child_session_id ?? "run"} ${row.outcome ?? "interrupted"}`;
|
|
159
|
+
}).join(", ")}`, LINE_MAX),
|
|
160
|
+
reports: rows.map((row) => ({
|
|
161
|
+
key: row.report_key,
|
|
162
|
+
childSessionId: row.child_session_id ?? void 0,
|
|
163
|
+
outcome: row.outcome ?? "interrupted",
|
|
164
|
+
context: readContext(row)
|
|
165
|
+
}))
|
|
166
|
+
}
|
|
167
|
+
}, `child-report:${[...keys].sort().join(",")}`);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
for (const key of keys) await database.run("UPDATE child_reports SET admit_failures = admit_failures + 1 WHERE report_key = ?", key);
|
|
170
|
+
if (Math.max(...rows.map((row) => Number(row.admit_failures))) + 1 === ADMIT_ATTEMPTS) onNotice(`A child session report is waiting for parent session ${parentSessionId}: ${oneLine(String(error), LINE_MAX)}`);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
await setState(keys, "delivered");
|
|
174
|
+
if (!revived) return;
|
|
175
|
+
const release = () => sessions.release?.(parentSessionId, { onlyIfIdle: true });
|
|
176
|
+
(receipt?.settled ?? Promise.resolve()).catch(() => void 0).then(release).catch((error) => onNotice(`Releasing revived parent session ${parentSessionId} failed: ${oneLine(String(error), LINE_MAX)}`));
|
|
177
|
+
};
|
|
178
|
+
const schedule = (parentSessionId) => {
|
|
179
|
+
const next = (delivering.get(parentSessionId) ?? Promise.resolve()).then(() => deliverParent(parentSessionId)).catch((error) => onNotice(`Child report delivery failed: ${oneLine(String(error), LINE_MAX)}`)).finally(() => {
|
|
180
|
+
if (delivering.get(parentSessionId) === next) delivering.delete(parentSessionId);
|
|
181
|
+
});
|
|
182
|
+
delivering.set(parentSessionId, next);
|
|
183
|
+
return next;
|
|
184
|
+
};
|
|
185
|
+
const sweep = async () => {
|
|
186
|
+
if (closed) return;
|
|
187
|
+
const open = await database.all("SELECT * FROM child_reports WHERE state = 'open'");
|
|
188
|
+
for (const row of open) {
|
|
189
|
+
const childSessionId = row.child_session_id;
|
|
190
|
+
if (sessions.isLive(childSessionId) || !sessions.directoryReady?.(row.workspace_id)) {
|
|
191
|
+
staleOpen.delete(row.report_key);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (!staleOpen.has(row.report_key)) {
|
|
195
|
+
staleOpen.add(row.report_key);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
staleOpen.delete(row.report_key);
|
|
199
|
+
const dormant = sessions.dormant?.().some((entry) => entry.sessionId === childSessionId);
|
|
200
|
+
await markReported(row, dormant ? "interrupted" : "cancelled", "", { errorClass: dormant ? "host_restart" : "child_closed" });
|
|
201
|
+
}
|
|
202
|
+
const parents = await database.all("SELECT DISTINCT parent_session_id FROM child_reports WHERE state = 'reported'");
|
|
203
|
+
await Promise.all(parents.map((row) => schedule(row.parent_session_id)));
|
|
204
|
+
};
|
|
205
|
+
const timer = options.sweepMs === 0 ? void 0 : setInterval(() => void sweep(), options.sweepMs ?? 15e3);
|
|
206
|
+
timer?.unref?.();
|
|
207
|
+
const ledger = {
|
|
208
|
+
async openEpisode(childSessionId) {
|
|
209
|
+
const child = sessions.scopes?.().find((entry) => entry.sessionId === childSessionId);
|
|
210
|
+
if (!child?.parentSessionId || !child.workspaceId) return void 0;
|
|
211
|
+
const latest = await latestEpisode(childSessionId);
|
|
212
|
+
if (latest?.state === "open") return toEpisode(latest);
|
|
213
|
+
const episode = Number(latest?.episode ?? 0) + 1;
|
|
214
|
+
await database.run("INSERT OR IGNORE INTO child_reports (report_key, child_session_id, episode, parent_session_id, workspace_id, state, updated_at) VALUES (?, ?, ?, ?, ?, 'open', ?)", episodeKey(childSessionId, episode), childSessionId, episode, child.parentSessionId, child.workspaceId, now());
|
|
215
|
+
return toEpisode(await latestEpisode(childSessionId));
|
|
216
|
+
},
|
|
217
|
+
async currentEpisode(childSessionId) {
|
|
218
|
+
return toEpisode(await latestEpisode(childSessionId));
|
|
219
|
+
},
|
|
220
|
+
async recordSteer(childSessionId, episode) {
|
|
221
|
+
const key = episodeKey(childSessionId, episode);
|
|
222
|
+
await database.run("UPDATE child_reports SET steers = steers + 1, updated_at = ? WHERE report_key = ? AND state = 'open'", now(), key);
|
|
223
|
+
const row = await database.get("SELECT steers FROM child_reports WHERE report_key = ?", key);
|
|
224
|
+
return Number(row?.steers ?? 0);
|
|
225
|
+
},
|
|
226
|
+
async reportFromChild({ childSessionId, outcome, text, fallback }) {
|
|
227
|
+
if (!OUTCOMES.has(outcome)) throw new TypeError(`Unknown child report outcome '${String(outcome)}'.`);
|
|
228
|
+
let row = await latestEpisode(childSessionId);
|
|
229
|
+
if (!row) {
|
|
230
|
+
await ledger.openEpisode(childSessionId);
|
|
231
|
+
row = await latestEpisode(childSessionId);
|
|
232
|
+
}
|
|
233
|
+
if (row?.state !== "open") return { duplicate: true };
|
|
234
|
+
await markReported(row, outcome, text, fallback);
|
|
235
|
+
schedule(row.parent_session_id);
|
|
236
|
+
return { duplicate: false };
|
|
237
|
+
},
|
|
238
|
+
async reportFromHost(input) {
|
|
239
|
+
if (!OUTCOMES.has(input.outcome)) throw new TypeError(`Unknown child report outcome '${String(input.outcome)}'.`);
|
|
240
|
+
const summary = oneLine(input.summary, LINE_MAX);
|
|
241
|
+
let row;
|
|
242
|
+
if (input.childSessionId) {
|
|
243
|
+
if (input.awaitChild) await ledger.openEpisode(input.childSessionId);
|
|
244
|
+
row = await latestEpisode(input.childSessionId);
|
|
245
|
+
if (row?.state === "open" && row.parent_session_id === input.parentSessionId) {
|
|
246
|
+
await database.run("UPDATE child_reports SET outcome = ?, summary = ?, context_json = ?, updated_at = ? WHERE report_key = ?", input.outcome, summary, JSON.stringify({
|
|
247
|
+
...readContext(row),
|
|
248
|
+
...boundContext(input.context)
|
|
249
|
+
}), now(), row.report_key);
|
|
250
|
+
return "merged";
|
|
251
|
+
}
|
|
252
|
+
if (row?.reported_at != null && input.unlessChildReportedSince !== void 0 && Number(row.reported_at) >= input.unlessChildReportedSince) return "skipped";
|
|
253
|
+
}
|
|
254
|
+
if (await database.get("SELECT report_key FROM child_reports WHERE report_key = ?", input.key)) return "skipped";
|
|
255
|
+
await database.run("INSERT INTO child_reports (report_key, child_session_id, episode, parent_session_id, workspace_id, state, outcome, summary, context_json, reported_at, updated_at) VALUES (?, ?, ?, ?, ?, 'reported', ?, ?, ?, ?, ?)", input.key, input.childSessionId ?? null, input.childSessionId ? Number(row?.episode ?? 0) + 1 : null, input.parentSessionId, input.workspaceId, input.outcome, summary, JSON.stringify(boundContext(input.context)), now(), now());
|
|
256
|
+
schedule(input.parentSessionId);
|
|
257
|
+
return "accepted";
|
|
258
|
+
},
|
|
259
|
+
attachParentSink(session, sink) {
|
|
260
|
+
const entry = {
|
|
261
|
+
workspaceId: session.workspaceId,
|
|
262
|
+
sink
|
|
263
|
+
};
|
|
264
|
+
sinks.set(session.sessionId, entry);
|
|
265
|
+
schedule(session.sessionId);
|
|
266
|
+
return () => {
|
|
267
|
+
if (sinks.get(session.sessionId) === entry) sinks.delete(session.sessionId);
|
|
268
|
+
};
|
|
269
|
+
},
|
|
270
|
+
sweep,
|
|
271
|
+
async close() {
|
|
272
|
+
closed = true;
|
|
273
|
+
if (timer) clearInterval(timer);
|
|
274
|
+
await Promise.allSettled(delivering.values());
|
|
275
|
+
await database.close();
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
return ledger;
|
|
279
|
+
}
|
|
280
|
+
//#endregion
|
|
281
|
+
//#region src/extensions/(backend)/root.server.ts
|
|
282
|
+
var root_server_default$1 = defineRoot((plugin) => ({
|
|
283
|
+
value: void 0,
|
|
284
|
+
services: [async (context) => {
|
|
285
|
+
await context.inject([
|
|
286
|
+
PO_FS_SERVICE,
|
|
287
|
+
PO_SQLITE_SERVICE,
|
|
288
|
+
PO_SERVER_SCOPE_SERVICE
|
|
289
|
+
], async (scoped) => {
|
|
290
|
+
const homeDirectory = plugin.host.context.homeDirectory;
|
|
291
|
+
if (!homeDirectory) throw new Error("Host links require an explicit host home directory.");
|
|
292
|
+
const environment = plugin.host.context.environment ?? {};
|
|
293
|
+
const peers = await createSessionPeers({
|
|
294
|
+
fs: requirePoFs(scoped),
|
|
295
|
+
homeDirectory,
|
|
296
|
+
environment
|
|
297
|
+
});
|
|
298
|
+
await peers.identity();
|
|
299
|
+
const directory = path.join(poHomeDirectory(homeDirectory, environment), "session");
|
|
300
|
+
await ensurePrivateDirectory(requirePoFs(scoped), directory, BACKGROUND_CONTEXT);
|
|
301
|
+
const database = await requirePoSqlite(scoped).open(path.join(directory, "groups.sqlite"), BACKGROUND_CONTEXT);
|
|
302
|
+
const groups = await createSessionGroupStore({ database });
|
|
303
|
+
await database.run("DELETE FROM session_group_members WHERE group_id IN (SELECT group_id FROM session_groups WHERE owner_authority = 'session-group-bridge')");
|
|
304
|
+
await database.run("DELETE FROM session_groups WHERE owner_authority = 'session-group-bridge'");
|
|
305
|
+
const bridge = createSessionGroupBridge({
|
|
306
|
+
groups,
|
|
307
|
+
peers,
|
|
308
|
+
onError: (error) => plugin.host.context.onNotice(`Group bridge failed: ${String(error)}`),
|
|
309
|
+
send: async (hostId, advert) => {
|
|
310
|
+
const config = peers.current();
|
|
311
|
+
const peer = config?.peers.find((entry) => entry.hostId === hostId);
|
|
312
|
+
if (!config || !peer) return;
|
|
313
|
+
await authenticatedPeerPost({
|
|
314
|
+
config,
|
|
315
|
+
peer,
|
|
316
|
+
path: "/api/plugins/session-peer/control",
|
|
317
|
+
value: {
|
|
318
|
+
type: "groups",
|
|
319
|
+
groups: advert
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
const scope = requirePoServerScope(scoped);
|
|
325
|
+
const releasePeers = plugin.host.scope === "host" ? await scope.provide(PO_SESSION_PEERS_CONTRACT, peers) : scoped.provide(PO_SESSION_PEERS_SERVICE, peers);
|
|
326
|
+
let releaseBridge;
|
|
327
|
+
try {
|
|
328
|
+
releaseBridge = plugin.host.scope === "host" ? await scope.provide(PO_SESSION_GROUP_BRIDGE_CONTRACT, bridge) : scoped.provide(PO_SESSION_GROUP_BRIDGE_SERVICE, bridge);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
await Promise.resolve(releasePeers());
|
|
331
|
+
await bridge.close();
|
|
332
|
+
throw error;
|
|
333
|
+
}
|
|
334
|
+
const sessions = plugin.host.context.sessionService;
|
|
335
|
+
let releaseLedger = () => void 0;
|
|
336
|
+
if (plugin.host.scope === "host" && sessions) try {
|
|
337
|
+
const ledger = await createChildReportLedger({
|
|
338
|
+
database: await requirePoSqlite(scoped).open(path.join(directory, "child-reports.sqlite"), BACKGROUND_CONTEXT),
|
|
339
|
+
sessions,
|
|
340
|
+
onNotice: (text) => plugin.host.context.onNotice(text)
|
|
341
|
+
});
|
|
342
|
+
const releaseContract = await scope.provide(PO_CHILD_REPORT_CONTRACT, ledger).catch(async (error) => {
|
|
343
|
+
await ledger.close();
|
|
344
|
+
throw error;
|
|
345
|
+
});
|
|
346
|
+
releaseLedger = async () => {
|
|
347
|
+
await Promise.resolve(releaseContract());
|
|
348
|
+
await ledger.close();
|
|
349
|
+
};
|
|
350
|
+
} catch (error) {
|
|
351
|
+
await releaseBridge();
|
|
352
|
+
await Promise.resolve(releasePeers());
|
|
353
|
+
await bridge.close();
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
return async () => {
|
|
357
|
+
await releaseLedger();
|
|
358
|
+
await releaseBridge();
|
|
359
|
+
await Promise.resolve(releasePeers());
|
|
360
|
+
await bridge.close();
|
|
361
|
+
};
|
|
362
|
+
});
|
|
363
|
+
}]
|
|
364
|
+
}));
|
|
365
|
+
const MAX_AGENT_RUN_TIMEOUT_MS = 72e5;
|
|
366
|
+
const POLL_MS = 1e3;
|
|
367
|
+
const NAME_MAX = 60;
|
|
368
|
+
const INPUT_KEYS = /* @__PURE__ */ new Set([
|
|
369
|
+
"task",
|
|
370
|
+
"systemPrompt",
|
|
371
|
+
"preset",
|
|
372
|
+
"modes",
|
|
373
|
+
"profile",
|
|
374
|
+
"domains",
|
|
375
|
+
"model",
|
|
376
|
+
"thinking",
|
|
377
|
+
"cwd",
|
|
378
|
+
"timeoutMs"
|
|
379
|
+
]);
|
|
380
|
+
const LAST_CONTROL_CODE = 31;
|
|
381
|
+
const DELETE_CODE = 127;
|
|
382
|
+
function hasControl(text) {
|
|
383
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
384
|
+
const code = text.charCodeAt(index);
|
|
385
|
+
if (code <= LAST_CONTROL_CODE || code === DELETE_CODE) return true;
|
|
386
|
+
}
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
/** A turn ended by these never produced a reply the caller can use. */
|
|
390
|
+
const UNFINISHED_STOPS = /* @__PURE__ */ new Set([
|
|
391
|
+
"error",
|
|
392
|
+
"aborted",
|
|
393
|
+
"toolUse"
|
|
394
|
+
]);
|
|
395
|
+
/** A value that becomes a harness flag argument on Node: no leading dash, no control characters, bounded. */
|
|
396
|
+
function name(field, value, list = false) {
|
|
397
|
+
if (typeof value !== "string") throw new TypeError(`agent: ${field} must be a string.`);
|
|
398
|
+
const text = value.trim();
|
|
399
|
+
if (text === "" || text.length > 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.`);
|
|
400
|
+
return text;
|
|
401
|
+
}
|
|
402
|
+
function names(field, value) {
|
|
403
|
+
if (!Array.isArray(value)) throw new TypeError(`agent: ${field} must be an array of names.`);
|
|
404
|
+
return [...new Set(value.map((entry) => name(field, entry, true)))];
|
|
405
|
+
}
|
|
406
|
+
/** Validates an agent run request at the trust boundary. Throws a TypeError naming the bad field. */
|
|
407
|
+
function parseAgentRunInput(value) {
|
|
408
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("agent: input must be an object with a task.");
|
|
409
|
+
const record = value;
|
|
410
|
+
for (const key of Object.keys(record)) {
|
|
411
|
+
if (key === "majorMode" || key === "minorModes") throw new TypeError(`agent: '${key}' is retired; use modes.`);
|
|
412
|
+
if (!INPUT_KEYS.has(key)) throw new TypeError(`agent: unknown field '${key}'.`);
|
|
413
|
+
}
|
|
414
|
+
const { task, systemPrompt, cwd, timeoutMs, profile } = record;
|
|
415
|
+
if (typeof task !== "string" || task.trim() === "") throw new TypeError("agent: task must be a non-empty string.");
|
|
416
|
+
if (systemPrompt !== void 0 && typeof systemPrompt !== "string") throw new TypeError("agent: systemPrompt must be a string.");
|
|
417
|
+
if (cwd !== void 0 && (typeof cwd !== "string" || !cwd.startsWith("/") || hasControl(cwd))) throw new TypeError("agent: cwd must be an absolute path.");
|
|
418
|
+
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}.`);
|
|
419
|
+
return {
|
|
420
|
+
task,
|
|
421
|
+
...systemPrompt === void 0 || systemPrompt === "" ? {} : { systemPrompt },
|
|
422
|
+
...record.preset === void 0 ? {} : { preset: name("preset", record.preset) },
|
|
423
|
+
...record.modes === void 0 ? {} : { modes: names("modes", record.modes) },
|
|
424
|
+
...profile === void 0 ? {} : { profile: profile === null ? null : name("profile", profile) },
|
|
425
|
+
...record.domains === void 0 ? {} : { domains: names("domains", record.domains) },
|
|
426
|
+
...record.model === void 0 ? {} : { model: name("model", record.model) },
|
|
427
|
+
...record.thinking === void 0 ? {} : { thinking: name("thinking", record.thinking) },
|
|
428
|
+
...cwd === void 0 ? {} : { cwd },
|
|
429
|
+
timeoutMs: timeoutMs ?? 6e5
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/** Same request, same hash: the parsed input with its keys in a fixed order, so `profile: null` and unset differ. */
|
|
433
|
+
async function agentRunHash(input) {
|
|
434
|
+
const ordered = Object.fromEntries([...INPUT_KEYS].filter((key) => key in input).map((key) => [key, input[key]]));
|
|
435
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(ordered)));
|
|
436
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
437
|
+
}
|
|
438
|
+
/** Over message entries newest first, the newest assistant message decides: a finished reply, an error or abort, or nothing usable. */
|
|
439
|
+
function finalReply(entries) {
|
|
440
|
+
for (const item of entries) {
|
|
441
|
+
const entry = item;
|
|
442
|
+
const message = entry?.type === "message" ? entry.message : void 0;
|
|
443
|
+
if (message?.role !== "assistant") continue;
|
|
444
|
+
const stop = typeof message.stopReason === "string" ? message.stopReason : "";
|
|
445
|
+
if (stop === "error") return {
|
|
446
|
+
status: "failed",
|
|
447
|
+
error: typeof message.errorMessage === "string" ? message.errorMessage : "The agent run failed."
|
|
448
|
+
};
|
|
449
|
+
if (stop === "aborted") return {
|
|
450
|
+
status: "stopped",
|
|
451
|
+
error: "The agent run was stopped."
|
|
452
|
+
};
|
|
453
|
+
if (UNFINISHED_STOPS.has(stop)) return void 0;
|
|
454
|
+
const content = message.content;
|
|
455
|
+
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();
|
|
456
|
+
return text === "" ? void 0 : {
|
|
457
|
+
status: "completed",
|
|
458
|
+
text
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
function selectionOf(input) {
|
|
463
|
+
const selection = {
|
|
464
|
+
...input.preset === void 0 ? {} : { preset: input.preset },
|
|
465
|
+
...input.modes === void 0 ? {} : { modes: input.modes },
|
|
466
|
+
...input.profile === void 0 ? {} : { profile: input.profile },
|
|
467
|
+
...input.domains === void 0 ? {} : { domains: input.domains }
|
|
468
|
+
};
|
|
469
|
+
return Object.keys(selection).length === 0 ? void 0 : selection;
|
|
470
|
+
}
|
|
471
|
+
function errorText(error) {
|
|
472
|
+
return error instanceof Error ? error.message : String(error);
|
|
473
|
+
}
|
|
474
|
+
/** Settles with `work`, or rejects once `signal` aborts; no timer or listener outlives it. */
|
|
475
|
+
function until(work, signal) {
|
|
476
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
477
|
+
let stop = () => void 0;
|
|
478
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
479
|
+
stop = () => reject(signal.reason);
|
|
480
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
481
|
+
});
|
|
482
|
+
return Promise.race([work, aborted]).finally(() => signal.removeEventListener("abort", stop));
|
|
483
|
+
}
|
|
484
|
+
function pause(ms, signal) {
|
|
485
|
+
let timer;
|
|
486
|
+
return until(new Promise((resolve) => {
|
|
487
|
+
timer = setTimeout(resolve, ms);
|
|
488
|
+
}), signal).finally(() => clearTimeout(timer));
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Runs tasks in unattended child sessions of one owning session. A child keeps the workflow-step provenance, so it
|
|
492
|
+
* stays out of the rail and reads like a step session once released.
|
|
493
|
+
*/
|
|
494
|
+
function createAgentRunService(dependencies) {
|
|
495
|
+
const { sessionId: parentSessionId, sessions } = dependencies;
|
|
496
|
+
const pollMs = dependencies.pollMs ?? POLL_MS;
|
|
497
|
+
return { async run(raw, options = {}) {
|
|
498
|
+
const input = parseAgentRunInput(raw);
|
|
499
|
+
const hash = await agentRunHash(input);
|
|
500
|
+
const cwd = input.cwd ?? dependencies.cwd;
|
|
501
|
+
if (!sessions?.prompt || !sessions.readExecutionState || !sessions.readMessages || cwd === void 0) return {
|
|
502
|
+
status: "failed",
|
|
503
|
+
output: "",
|
|
504
|
+
error: "This host cannot run agent sessions."
|
|
505
|
+
};
|
|
506
|
+
const timeout = AbortSignal.timeout(input.timeoutMs);
|
|
507
|
+
const signal = AbortSignal.any([
|
|
508
|
+
dependencies.lifetime,
|
|
509
|
+
timeout,
|
|
510
|
+
...options.signal === void 0 ? [] : [options.signal]
|
|
511
|
+
]);
|
|
512
|
+
const owned = { parentSessionId };
|
|
513
|
+
let sessionId;
|
|
514
|
+
let result;
|
|
515
|
+
try {
|
|
516
|
+
const selection = selectionOf(input);
|
|
517
|
+
sessionId = (await sessions.create({
|
|
518
|
+
cwd,
|
|
519
|
+
name: `Agent: ${input.task.trim().split("\n", 1)[0].slice(0, NAME_MAX)}`,
|
|
520
|
+
parentSessionId,
|
|
521
|
+
sessionProvenance: WORKFLOW_STEP_SESSION_PROVENANCE,
|
|
522
|
+
interaction: "unattended",
|
|
523
|
+
...selection === void 0 ? {} : { selection },
|
|
524
|
+
...input.model === void 0 ? {} : { model: input.model },
|
|
525
|
+
...input.thinking === void 0 ? {} : { thinking: input.thinking },
|
|
526
|
+
...input.systemPrompt === void 0 ? {} : { appendSystemPrompt: input.systemPrompt },
|
|
527
|
+
signal
|
|
528
|
+
})).sessionId;
|
|
529
|
+
options.onStarted?.(sessionId, hash);
|
|
530
|
+
await until((await sessions.prompt(sessionId, input.task, {
|
|
531
|
+
...owned,
|
|
532
|
+
signal
|
|
533
|
+
})).settled, signal);
|
|
534
|
+
for (;;) {
|
|
535
|
+
const state = await sessions.readExecutionState(sessionId, owned);
|
|
536
|
+
if (state.isIdle && !state.hasPendingMessages && !(state.backgroundWork?.items.some(holdsSettledSession) ?? false) && ((await dependencies.approvals()?.unsettled(sessionId))?.length ?? 0) === 0) break;
|
|
537
|
+
await pause(pollMs, signal);
|
|
538
|
+
}
|
|
539
|
+
const reply = finalReply(await sessions.readMessages(sessionId, {
|
|
540
|
+
...owned,
|
|
541
|
+
limit: 20
|
|
542
|
+
}));
|
|
543
|
+
result = reply === void 0 ? {
|
|
544
|
+
sessionId,
|
|
545
|
+
status: "failed",
|
|
546
|
+
output: "",
|
|
547
|
+
error: "The agent ended without a reply."
|
|
548
|
+
} : reply.status === "completed" ? {
|
|
549
|
+
sessionId,
|
|
550
|
+
status: "completed",
|
|
551
|
+
output: reply.text
|
|
552
|
+
} : {
|
|
553
|
+
sessionId,
|
|
554
|
+
status: reply.status,
|
|
555
|
+
output: "",
|
|
556
|
+
error: reply.error
|
|
557
|
+
};
|
|
558
|
+
} catch (error) {
|
|
559
|
+
result = {
|
|
560
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
561
|
+
status: signal.aborted && !timeout.aborted ? "stopped" : "failed",
|
|
562
|
+
output: "",
|
|
563
|
+
error: timeout.aborted ? `The agent did not finish within ${input.timeoutMs}ms.` : errorText(error)
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
if (sessionId !== void 0) {
|
|
567
|
+
const child = sessionId;
|
|
568
|
+
const cleanup = async (step) => {
|
|
569
|
+
try {
|
|
570
|
+
await step();
|
|
571
|
+
} catch (error) {
|
|
572
|
+
dependencies.onError?.(error);
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
if (signal.aborted) await cleanup(() => sessions.abort?.(child, owned));
|
|
576
|
+
await cleanup(() => dependencies.approvals()?.abandon(child));
|
|
577
|
+
await cleanup(() => sessions.release?.(child, owned));
|
|
578
|
+
}
|
|
579
|
+
return result;
|
|
580
|
+
} };
|
|
581
|
+
}
|
|
582
|
+
const IDLE_DEBOUNCE_MS = 2e3;
|
|
583
|
+
const ERROR_MAX = 300;
|
|
584
|
+
/** The text a child gets when it idles without telling its parent how the work ended. */
|
|
585
|
+
function childReportSteerText(parentSessionId) {
|
|
586
|
+
return [
|
|
587
|
+
"Your parent session is waiting for the result of this work and has not heard from you.",
|
|
588
|
+
"If work remains, finish it first. Then report once, in code mode:",
|
|
589
|
+
`network.send({ to: '${parentSessionId}', terminal: true, outcome: 'done' | 'blocked' | 'failed', text: '<result, or the exact blocker and what you need>' })`
|
|
590
|
+
].join("\n");
|
|
591
|
+
}
|
|
592
|
+
/** The newest assistant message's stop reason, to tell a model failure from a quiet stop. */
|
|
593
|
+
async function lastStop(session) {
|
|
594
|
+
for await (const entry of session.entriesNewestFirst({
|
|
595
|
+
type: "message",
|
|
596
|
+
limit: 20
|
|
597
|
+
})) {
|
|
598
|
+
const message = entry.message;
|
|
599
|
+
if (message?.role !== "assistant") continue;
|
|
600
|
+
return message.stopReason === "error" ? { error: oneLine(typeof message.errorMessage === "string" ? message.errorMessage : "Model error.", ERROR_MAX) } : {};
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Child side of terminal reporting: holds the child live while its episode is open, and when it idles
|
|
605
|
+
* without reporting, reminds it (at most twice) before the host files a fallback report for it.
|
|
606
|
+
*/
|
|
607
|
+
function createChildReportGate(options) {
|
|
608
|
+
const { sessionId, ledger } = options;
|
|
609
|
+
let holding = false;
|
|
610
|
+
let timer;
|
|
611
|
+
let closed = false;
|
|
612
|
+
const setHolding = (value) => {
|
|
613
|
+
if (holding === value) return;
|
|
614
|
+
holding = value;
|
|
615
|
+
options.onHoldChange();
|
|
616
|
+
};
|
|
617
|
+
const refresh = async () => {
|
|
618
|
+
const episode = await ledger.currentEpisode(sessionId);
|
|
619
|
+
if (!closed) setHolding(episode?.state === "open");
|
|
620
|
+
return episode;
|
|
621
|
+
};
|
|
622
|
+
const fallback = async (outcome, errorClass, text, error) => {
|
|
623
|
+
await ledger.reportFromChild({
|
|
624
|
+
childSessionId: sessionId,
|
|
625
|
+
outcome,
|
|
626
|
+
text: text ?? "",
|
|
627
|
+
fallback: {
|
|
628
|
+
errorClass,
|
|
629
|
+
...error ? { error: oneLine(error, ERROR_MAX) } : {}
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
await refresh();
|
|
633
|
+
};
|
|
634
|
+
const check = async () => {
|
|
635
|
+
const session = options.session();
|
|
636
|
+
if (closed || !session) return;
|
|
637
|
+
const activity = await session.activity();
|
|
638
|
+
if (!activity.isIdle || activity.hasPendingMessages || options.otherWorkPending()) return;
|
|
639
|
+
const episode = await refresh();
|
|
640
|
+
if (closed || episode?.state !== "open") return;
|
|
641
|
+
const last = await lastAssistantText(session);
|
|
642
|
+
const stop = await lastStop(session);
|
|
643
|
+
if (stop?.error) return fallback("failed", "model_error", last, stop.error);
|
|
644
|
+
if (episode.steers >= 2 || !options.canSteer() || !session.admitMessage) return fallback("interrupted", "steer_cap", last);
|
|
645
|
+
const steer = await ledger.recordSteer(sessionId, episode.episode);
|
|
646
|
+
try {
|
|
647
|
+
await session.admitMessage({
|
|
648
|
+
type: PO_CHILD_REPORT_STEER_TYPE,
|
|
649
|
+
text: childReportSteerText(options.parentSessionId),
|
|
650
|
+
display: true,
|
|
651
|
+
details: {
|
|
652
|
+
episode: episode.episode,
|
|
653
|
+
steer
|
|
654
|
+
}
|
|
655
|
+
}, "followUp", `child-report-steer:${sessionId}:${episode.episode}:${steer}`);
|
|
656
|
+
} catch (error) {
|
|
657
|
+
await fallback("failed", "faulted", last, String(error));
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
const schedule = () => {
|
|
661
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
662
|
+
timer = setTimeout(() => {
|
|
663
|
+
timer = void 0;
|
|
664
|
+
check().catch(options.onError);
|
|
665
|
+
}, options.delayMs ?? IDLE_DEBOUNCE_MS);
|
|
666
|
+
};
|
|
667
|
+
return {
|
|
668
|
+
get holding() {
|
|
669
|
+
return holding;
|
|
670
|
+
},
|
|
671
|
+
/** Restores the hold after a restart or reload, and checks a child that came back idle. */
|
|
672
|
+
async start() {
|
|
673
|
+
if ((await refresh())?.state === "open") schedule();
|
|
674
|
+
},
|
|
675
|
+
/** A run ended. The first one opens episode 1; an aborted run is the person's, so it is left alone. */
|
|
676
|
+
async settled(event) {
|
|
677
|
+
if (closed || event.aborted === true) return;
|
|
678
|
+
const episode = await ledger.currentEpisode(sessionId) ?? await ledger.openEpisode(sessionId);
|
|
679
|
+
if (closed) return;
|
|
680
|
+
setHolding(episode?.state === "open");
|
|
681
|
+
if (episode?.state === "open") schedule();
|
|
682
|
+
},
|
|
683
|
+
/** The child reported itself; drop the hold. */
|
|
684
|
+
refresh,
|
|
685
|
+
close() {
|
|
686
|
+
closed = true;
|
|
687
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
688
|
+
timer = void 0;
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
//#endregion
|
|
693
|
+
//#region src/services/networkNamespace/index.ts
|
|
694
|
+
/** What a child may say about its own work. The host files `interrupted` itself. */
|
|
695
|
+
const CHILD_OUTCOMES = [
|
|
696
|
+
"done",
|
|
697
|
+
"blocked",
|
|
698
|
+
"failed",
|
|
699
|
+
"cancelled"
|
|
700
|
+
];
|
|
701
|
+
/** `{ to, text, urgent?, terminal?, outcome? }`, validated at the namespace boundary. `urgent` exists only where the host has lanes. */
|
|
702
|
+
function parseSend(raw, lanes, terminal = false) {
|
|
703
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Expected an object.");
|
|
704
|
+
const { urgent, terminal: isTerminal, outcome, ...rest } = raw;
|
|
705
|
+
if (urgent !== void 0 && !lanes) throw new Error("Unknown operation field.");
|
|
706
|
+
if (urgent !== void 0 && typeof urgent !== "boolean") throw new Error("urgent must be a boolean.");
|
|
707
|
+
if (!terminal && (isTerminal !== void 0 || outcome !== void 0)) throw new Error("Unknown operation field.");
|
|
708
|
+
if (isTerminal !== void 0 && typeof isTerminal !== "boolean") throw new Error("terminal must be a boolean.");
|
|
709
|
+
if (outcome !== void 0 && isTerminal !== true) throw new Error("outcome needs terminal: true.");
|
|
710
|
+
if (outcome !== void 0 && !CHILD_OUTCOMES.includes(outcome)) throw new Error(`outcome must be one of ${CHILD_OUTCOMES.join(", ")}.`);
|
|
711
|
+
const { to, text } = fields(rest, ["to", "text"]);
|
|
712
|
+
return {
|
|
713
|
+
to,
|
|
714
|
+
text,
|
|
715
|
+
urgent: urgent === true,
|
|
716
|
+
...isTerminal === true ? { terminal: outcome ?? "done" } : {}
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
/** Records one outgoing message in the run, so a view of the exec call can show what was said and to whom. */
|
|
720
|
+
async function recorded(run, name, input, call) {
|
|
721
|
+
const started = Date.now();
|
|
722
|
+
const base = {
|
|
723
|
+
name,
|
|
724
|
+
tool: name,
|
|
725
|
+
args: typeof input === "object" && input !== null && !Array.isArray(input) ? { ...input } : {}
|
|
726
|
+
};
|
|
727
|
+
try {
|
|
728
|
+
const value = await call();
|
|
729
|
+
run.record?.({
|
|
730
|
+
...base,
|
|
731
|
+
ok: true,
|
|
732
|
+
ms: Date.now() - started,
|
|
733
|
+
result: {
|
|
734
|
+
content: [{
|
|
735
|
+
type: "text",
|
|
736
|
+
text: JSON.stringify(value, null, 2) ?? ""
|
|
737
|
+
}],
|
|
738
|
+
details: value
|
|
739
|
+
}
|
|
740
|
+
});
|
|
741
|
+
return value;
|
|
742
|
+
} catch (error) {
|
|
743
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
744
|
+
run.record?.({
|
|
745
|
+
...base,
|
|
746
|
+
ok: false,
|
|
747
|
+
ms: Date.now() - started,
|
|
748
|
+
error: message,
|
|
749
|
+
result: { content: [{
|
|
750
|
+
type: "text",
|
|
751
|
+
text: message
|
|
752
|
+
}] }
|
|
753
|
+
});
|
|
754
|
+
throw error;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
const OUT_OF_SCOPE = "Session is outside your communication scope.";
|
|
758
|
+
/** A session name long enough to recognise and short enough to fit the approval card title. */
|
|
759
|
+
const TITLE_NAME_MAX = 80;
|
|
760
|
+
const MESSAGE_PREVIEW_MAX = 300;
|
|
761
|
+
const TERMINAL_FIELDS = `; terminal?: boolean; outcome?: ${CHILD_OUTCOMES.map((outcome) => `'${outcome}'`).join(" | ")}`;
|
|
762
|
+
/**
|
|
763
|
+
* Asks the person before messaging a live session whose `@session:` mention expired when this session compacted.
|
|
764
|
+
* Every other target runs without asking: a live mention or a shared group passes, and anything else is refused.
|
|
765
|
+
*/
|
|
766
|
+
function expiredMentionApproval(operations, verb, parse, t) {
|
|
767
|
+
return {
|
|
768
|
+
requirement: "human",
|
|
769
|
+
applies: (raw) => {
|
|
770
|
+
const to = raw?.to;
|
|
771
|
+
return typeof to === "string" && to !== "" && operations.mentionApprovalTarget?.(to) !== void 0;
|
|
772
|
+
},
|
|
773
|
+
resolve: ([raw]) => {
|
|
774
|
+
const { to, text, urgent } = parse(raw);
|
|
775
|
+
const target = operations.mentionApprovalTarget?.(to);
|
|
776
|
+
if (target === void 0) throw new Error(OUT_OF_SCOPE);
|
|
777
|
+
return [{
|
|
778
|
+
to: target.sessionId,
|
|
779
|
+
text,
|
|
780
|
+
...urgent ? { urgent } : {}
|
|
781
|
+
}];
|
|
782
|
+
},
|
|
783
|
+
describe: (raw) => {
|
|
784
|
+
const { to, text } = parse(raw);
|
|
785
|
+
const name = operations.mentionApprovalTarget?.(to)?.name ?? to;
|
|
786
|
+
return {
|
|
787
|
+
source: t("session.approval.source", "Sessions"),
|
|
788
|
+
title: verb === "ask" ? t("session.approval.askAgain", "Let this session ask {name} again", { name: name.slice(0, TITLE_NAME_MAX) }) : t("session.approval.messageAgain", "Let this session message {name} again", { name: name.slice(0, TITLE_NAME_MAX) }),
|
|
789
|
+
summary: t("session.approval.restoreMention", "The earlier @session: mention expired when this session compacted. Approving restores access until the next compaction and delivers this message."),
|
|
790
|
+
details: [{
|
|
791
|
+
label: t("session.approval.session", "Session"),
|
|
792
|
+
value: name
|
|
793
|
+
}, {
|
|
794
|
+
label: t("session.approval.message", "Message"),
|
|
795
|
+
value: text.slice(0, MESSAGE_PREVIEW_MAX)
|
|
796
|
+
}]
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
/** Messaging between sessions on this host and linked hosts, with Team intercom's send, ask, reply and pending. */
|
|
802
|
+
function createNetworkNamespace(options) {
|
|
803
|
+
assertCodemodeNamespaceName("network");
|
|
804
|
+
const { operations, terminal } = options;
|
|
805
|
+
const t = options.translate ?? ((_key, fallback, vars) => formatMessage(fallback, vars));
|
|
806
|
+
const parse = (raw) => parseSend(raw, operations.lanes === true, terminal !== void 0);
|
|
807
|
+
const parseAsk = (raw) => {
|
|
808
|
+
const { to, text } = fields(raw, ["to", "text"]);
|
|
809
|
+
return {
|
|
810
|
+
to,
|
|
811
|
+
text
|
|
812
|
+
};
|
|
813
|
+
};
|
|
814
|
+
return {
|
|
815
|
+
name: "network",
|
|
816
|
+
summary: "Message sessions on this host and linked hosts: send, ask with a tracked reply, answer questions, and keep a coordinator logbook.",
|
|
817
|
+
portable: true,
|
|
818
|
+
...operations.mentionApprovalTarget === void 0 ? {} : { approval: {
|
|
819
|
+
send: expiredMentionApproval(operations, "message", parse, t),
|
|
820
|
+
...operations.ask ? { ask: expiredMentionApproval(operations, "ask", parseAsk, t) } : {}
|
|
821
|
+
} },
|
|
822
|
+
declarations: `declare const network: {
|
|
823
|
+
list(): Promise<unknown>;
|
|
824
|
+
${`${operations.lanes ? `/** Queued: arrives in one digest when the recipient's run ends. urgent joins its running turn. Both are budgeted per session. */
|
|
825
|
+
send(input: { to: string; text: string; urgent?: boolean${terminal ? TERMINAL_FIELDS : ""} }): Promise<unknown>;` : `send(input: { to: string; text: string${terminal ? TERMINAL_FIELDS : ""} }): Promise<unknown>;`}${terminal ? `\n /** terminal: true reports how your work for parent session '${terminal.parentSessionId}' ended, once per piece of work; to must be that parent. */` : ""}`}
|
|
826
|
+
${operations.ask ? `/** Joins the recipient's running turn, so it spends the interrupt budget. The reply arrives later as a message. */
|
|
827
|
+
ask(input: { to: string; text: string }): Promise<{ requestId: string }>;` : ""}
|
|
828
|
+
${operations.reply ? "reply(input: { requestId: string; text: string }): Promise<unknown>;" : ""}
|
|
829
|
+
${operations.pending ? "pending(): Promise<{ requestId: string; from: string }[]>;" : ""}
|
|
830
|
+
${operations.log ? `/** Append to your coordinator's logbook (hierarchy only, never a group). 'blocked' wakes it, batched; the host files your stop report itself. Empty to: no coordinator. */
|
|
831
|
+
log(input: { text: string; level?: 'info' | 'blocked' }): Promise<{ to: string[] }>;` : ""}
|
|
832
|
+
${operations.logbook ? `/** Your own logbook as a coordinator, newest first. limit defaults to 20, at most 100. */
|
|
833
|
+
logbook(input?: { unread?: boolean; sessionId?: string; offset?: number; limit?: number }): Promise<{
|
|
834
|
+
entries: { id: string; from: string; name?: string; level: 'info' | 'blocked'; text: string; at?: string; read: boolean }[];
|
|
835
|
+
total: number;
|
|
836
|
+
nextOffset?: number;
|
|
837
|
+
}>;` : ""}
|
|
838
|
+
${operations.markRead ? "markRead(input: { ids: string[] }): Promise<{ marked: number }>;" : ""}
|
|
839
|
+
};`,
|
|
840
|
+
bind(run) {
|
|
841
|
+
if (run.sessionId !== options.sessionId) throw new Error("Network namespace belongs to another session.");
|
|
842
|
+
const lifetime = new AbortController();
|
|
843
|
+
const signal = AbortSignal.any([run.signal, lifetime.signal]);
|
|
844
|
+
run.onDispose(() => lifetime.abort(/* @__PURE__ */ new Error("Network code-mode run is disposed.")));
|
|
845
|
+
const check = () => {
|
|
846
|
+
if (run.caller !== "main") throw new Error("Network operations require the main agent.");
|
|
847
|
+
signal.throwIfAborted();
|
|
848
|
+
options.assertAvailable();
|
|
849
|
+
};
|
|
850
|
+
const methods = Object.create(null);
|
|
851
|
+
methods.list = async () => {
|
|
852
|
+
check();
|
|
853
|
+
const result = await operations.list(signal);
|
|
854
|
+
check();
|
|
855
|
+
return detach(result);
|
|
856
|
+
};
|
|
857
|
+
methods.send = (raw) => recorded(run, "network.send", raw, async () => {
|
|
858
|
+
check();
|
|
859
|
+
const { to, text, urgent, terminal: outcome } = parse(raw);
|
|
860
|
+
if (outcome !== void 0 && terminal) {
|
|
861
|
+
if (to !== terminal.parentSessionId) throw new Error(`A terminal report goes to your parent session '${terminal.parentSessionId}' only.`);
|
|
862
|
+
const report = await terminal.report(outcome, text);
|
|
863
|
+
if (report) return {
|
|
864
|
+
to,
|
|
865
|
+
reported: true,
|
|
866
|
+
...report.duplicate ? { duplicate: true } : {}
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
if (run.approvedCall !== void 0) operations.restoreMention?.(to);
|
|
870
|
+
const result = await (urgent ? operations.send(to, text, signal, { urgent }) : operations.send(to, text, signal));
|
|
871
|
+
const resolved = result?.to;
|
|
872
|
+
options.rearm?.(typeof resolved === "string" ? resolved : to);
|
|
873
|
+
return detach(result);
|
|
874
|
+
});
|
|
875
|
+
if (operations.ask) methods.ask = (raw) => recorded(run, "network.ask", raw, async () => {
|
|
876
|
+
check();
|
|
877
|
+
const { to, text } = parseAsk(raw);
|
|
878
|
+
if (run.approvedCall !== void 0) operations.restoreMention?.(to);
|
|
879
|
+
const result = await operations.ask(to, text, signal);
|
|
880
|
+
options.rearm?.(to);
|
|
881
|
+
return detach(result);
|
|
882
|
+
});
|
|
883
|
+
if (operations.reply) methods.reply = (raw) => recorded(run, "network.reply", raw, async () => {
|
|
884
|
+
check();
|
|
885
|
+
const { requestId, text } = fields(raw, ["requestId", "text"]);
|
|
886
|
+
return detach(await operations.reply(requestId, text, signal));
|
|
887
|
+
});
|
|
888
|
+
if (operations.pending) methods.pending = async () => {
|
|
889
|
+
check();
|
|
890
|
+
const result = await operations.pending(signal);
|
|
891
|
+
check();
|
|
892
|
+
return detach(result);
|
|
893
|
+
};
|
|
894
|
+
if (operations.log) methods.log = async (raw) => {
|
|
895
|
+
check();
|
|
896
|
+
const { text, level } = parseLogInput(raw);
|
|
897
|
+
return detach(await operations.log(text, level, signal));
|
|
898
|
+
};
|
|
899
|
+
if (operations.logbook) methods.logbook = async (raw) => {
|
|
900
|
+
check();
|
|
901
|
+
const result = await operations.logbook(parseLogbookQuery(raw), signal);
|
|
902
|
+
check();
|
|
903
|
+
return detach(result);
|
|
904
|
+
};
|
|
905
|
+
if (operations.markRead) methods.markRead = async (raw) => {
|
|
906
|
+
check();
|
|
907
|
+
return detach(await operations.markRead(parseMarkReadInput(raw), signal));
|
|
908
|
+
};
|
|
909
|
+
return methods;
|
|
910
|
+
}
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
//#endregion
|
|
7
914
|
//#region src/services/peerInbox/index.ts
|
|
8
915
|
const inboxes = /* @__PURE__ */ new Map();
|
|
9
916
|
/**
|
|
@@ -23,94 +930,435 @@ async function deliverSessionPeerEnvelope(targetSessionId, sourceKey, type, payl
|
|
|
23
930
|
}
|
|
24
931
|
//#endregion
|
|
25
932
|
//#region src/extensions/workspaces/sessions/(backend)/root.server.ts
|
|
933
|
+
/** How much of its own work a session is reminded of at the end of a peer's message. */
|
|
934
|
+
const WORK_ANCHOR_MAX = 800;
|
|
935
|
+
/** The outbox record of a session this one started, so it counts as engaged with it. */
|
|
936
|
+
const ENGAGE_KIND = "session-engage";
|
|
937
|
+
/** Admits an intercom notice into the session itself, to be read when its run ends. */
|
|
938
|
+
async function remindSession(agent, text, requestId, details) {
|
|
939
|
+
const session = agent.context.session;
|
|
940
|
+
if (session?.admitMessage) await session.admitMessage({
|
|
941
|
+
type: INTERCOM_MESSAGE_TYPE,
|
|
942
|
+
text,
|
|
943
|
+
display: true,
|
|
944
|
+
details
|
|
945
|
+
}, "followUp", requestId);
|
|
946
|
+
else await session?.admitPrompt?.(text, "followUp", void 0, requestId);
|
|
947
|
+
}
|
|
26
948
|
var root_server_default = defineRoot((pluginContext) => ({
|
|
27
949
|
value: void 0,
|
|
28
|
-
services: [
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
communication: peerCommunication,
|
|
66
|
-
authorizePeer: (peerKey, metadata) => groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey),
|
|
67
|
-
admitPrompt: (prompt, admission, requestId) => session.admitPrompt(prompt, admission, void 0, requestId)
|
|
950
|
+
services: [
|
|
951
|
+
provideBackgroundWorkService,
|
|
952
|
+
(owner) => {
|
|
953
|
+
const agent = pluginContext.agent;
|
|
954
|
+
if (!agent) return;
|
|
955
|
+
const options = {
|
|
956
|
+
sessionId: agent.context.sessionId,
|
|
957
|
+
provenance: () => pluginContext.host.context.sessionContext?.provenance,
|
|
958
|
+
coordination: () => pluginContext.host.context.coordination,
|
|
959
|
+
started: async (sessionId) => {
|
|
960
|
+
try {
|
|
961
|
+
await readPoSessionDelivery(owner)?.record({
|
|
962
|
+
recipientKey: sessionId,
|
|
963
|
+
kind: ENGAGE_KIND
|
|
964
|
+
});
|
|
965
|
+
} catch (error) {
|
|
966
|
+
pluginContext.host.context.onNotice(`Engage record failed: ${String(error)}`);
|
|
967
|
+
}
|
|
968
|
+
},
|
|
969
|
+
operations: readSessionOperations(owner) ?? createNodeSessionOperations(pluginContext.host, owner, agent.context.sessionId, (text, requestId, details) => remindSession(agent, text, requestId, details)),
|
|
970
|
+
assertAvailable: () => pluginContext.signal.throwIfAborted()
|
|
971
|
+
};
|
|
972
|
+
const tool = agent.registerTool(createStartSessionTool(options));
|
|
973
|
+
let session = agent.context.session;
|
|
974
|
+
const stop = createStopReport({
|
|
975
|
+
delayMs: STOP_REPORT_DELAY_MS,
|
|
976
|
+
activity: async () => await session?.activity() ?? {
|
|
977
|
+
isIdle: false,
|
|
978
|
+
hasPendingMessages: false
|
|
979
|
+
},
|
|
980
|
+
holding: () => readPoBackgroundWorkService(owner)?.snapshot().items.some(holdsSettledSession) === true,
|
|
981
|
+
report: async () => {
|
|
982
|
+
if (!session || !options.operations.log) return;
|
|
983
|
+
const text = await lastAssistantText(session) ?? "No reply yet.";
|
|
984
|
+
await options.operations.log(text, STOP_LEVEL, pluginContext.signal);
|
|
985
|
+
},
|
|
986
|
+
onError: (error) => pluginContext.host.context.onNotice(`Stop report failed: ${String(error)}`)
|
|
68
987
|
});
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const directory = createSessionDirectory({ authorizeDiscovery: async (caller, subject) => {
|
|
77
|
-
const reference = peerSessionReference(subject.hostId, subject.sessionId);
|
|
78
|
-
return (await groups.groupsFor(caller)).some((group) => group.members.includes(reference)) ? { capabilities: ["message"] } : void 0;
|
|
79
|
-
} });
|
|
80
|
-
for (const peer of peerConfig.peers) for (const sessionId of peer.allowedSessionIds) directory.observe({
|
|
81
|
-
hostId: peer.hostId,
|
|
82
|
-
sessionId,
|
|
83
|
-
hostIncarnation: "unknown",
|
|
84
|
-
sessionIncarnation: "unknown",
|
|
85
|
-
sequence: 0,
|
|
86
|
-
observedAt: 0,
|
|
87
|
-
staleAfterMs: 0,
|
|
88
|
-
deliveryTarget: peerSessionReference(peer.hostId, sessionId),
|
|
89
|
-
reachability: "unknown",
|
|
90
|
-
runtime: "unknown",
|
|
91
|
-
activity: "unknown",
|
|
92
|
-
voice: {
|
|
93
|
-
eligible: "unknown",
|
|
94
|
-
readiness: "unknown"
|
|
988
|
+
const settled = agent.registerHook(defineHook({
|
|
989
|
+
name: "session-report-sustained-stop",
|
|
990
|
+
description: "Update the session snapshot and schedule a coordinator report when the session stays stopped.",
|
|
991
|
+
event: "agent_settled",
|
|
992
|
+
handle: (_event, execution) => {
|
|
993
|
+
session = execution.session;
|
|
994
|
+
stop.settled();
|
|
95
995
|
}
|
|
996
|
+
}));
|
|
997
|
+
const eligibility = options.provenance() === COORDINATOR_SESSION_PROVENANCE ? void 0 : agent.registerToolRestriction({ excludedTools: [START_SESSION_TOOL_NAME] });
|
|
998
|
+
const notice = (label) => (error) => pluginContext.host.context.onNotice(`${label}: ${String(error)}`);
|
|
999
|
+
const sessionContext = pluginContext.host.context.sessionContext;
|
|
1000
|
+
const parentSessionId = reportsToParent(sessionContext) ? sessionContext?.parentSessionId : void 0;
|
|
1001
|
+
let ledger;
|
|
1002
|
+
let gate;
|
|
1003
|
+
const networkOptions = {
|
|
1004
|
+
...options,
|
|
1005
|
+
...parentSessionId ? { terminal: {
|
|
1006
|
+
parentSessionId,
|
|
1007
|
+
report: async (outcome, text) => {
|
|
1008
|
+
if (!ledger) return void 0;
|
|
1009
|
+
const result = await ledger.reportFromChild({
|
|
1010
|
+
childSessionId: options.sessionId,
|
|
1011
|
+
outcome,
|
|
1012
|
+
text
|
|
1013
|
+
});
|
|
1014
|
+
await gate?.refresh();
|
|
1015
|
+
return result;
|
|
1016
|
+
}
|
|
1017
|
+
} } : {},
|
|
1018
|
+
rearm: (to) => {
|
|
1019
|
+
const child = pluginContext.host.context.sessionService?.scopes?.().find((scope) => scope.sessionId === to || scope.name === to);
|
|
1020
|
+
if (!ledger || child?.parentSessionId !== options.sessionId) return;
|
|
1021
|
+
ledger.openEpisode(child.sessionId).catch(notice("Child report episode failed"));
|
|
1022
|
+
}
|
|
1023
|
+
};
|
|
1024
|
+
const reporting = owner.inject([PO_SERVER_SCOPE_SERVICE, PO_BACKGROUND_WORK_SERVICE], (context) => {
|
|
1025
|
+
const resolved = requirePoServerScope(context).resolve(PO_CHILD_REPORT_CONTRACT);
|
|
1026
|
+
if (!resolved) return;
|
|
1027
|
+
ledger = resolved;
|
|
1028
|
+
const releases = [];
|
|
1029
|
+
if (sessionContext?.workspaceId) {
|
|
1030
|
+
const attach = () => resolved.attachParentSink({
|
|
1031
|
+
sessionId: options.sessionId,
|
|
1032
|
+
workspaceId: sessionContext.workspaceId
|
|
1033
|
+
}, { admit: async (message, requestId) => {
|
|
1034
|
+
const current = session ?? agent.context.session;
|
|
1035
|
+
if (!current?.admitMessage) throw new Error("The session cannot admit a child report.");
|
|
1036
|
+
return await current.admitMessage(message, "followUp", requestId);
|
|
1037
|
+
} });
|
|
1038
|
+
let detachSink = attach();
|
|
1039
|
+
const ready = agent.registerHook(defineHook({
|
|
1040
|
+
name: "session-reattach-child-report-sink",
|
|
1041
|
+
description: "Reattach the child report sink when the session is ready to admit waiting reports.",
|
|
1042
|
+
event: "session_ready",
|
|
1043
|
+
handle: () => {
|
|
1044
|
+
detachSink();
|
|
1045
|
+
detachSink = attach();
|
|
1046
|
+
}
|
|
1047
|
+
}));
|
|
1048
|
+
releases.push(() => {
|
|
1049
|
+
ready.dispose();
|
|
1050
|
+
detachSink();
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
if (parentSessionId) {
|
|
1054
|
+
const work = readPoBackgroundWorkService(context);
|
|
1055
|
+
let handle;
|
|
1056
|
+
const childGate = createChildReportGate({
|
|
1057
|
+
sessionId: options.sessionId,
|
|
1058
|
+
parentSessionId,
|
|
1059
|
+
ledger: resolved,
|
|
1060
|
+
session: () => session ?? agent.context.session,
|
|
1061
|
+
otherWorkPending: () => work?.snapshot(options.sessionId).items.some((item) => item.provider !== PO_CHILD_REPORT_WORK_PROVIDER && awaitsCompletion(item)) === true,
|
|
1062
|
+
canSteer: () => readPoCodemode(context) !== void 0,
|
|
1063
|
+
onHoldChange: () => handle?.update(),
|
|
1064
|
+
onError: notice("Child report check failed")
|
|
1065
|
+
});
|
|
1066
|
+
gate = childGate;
|
|
1067
|
+
handle = work?.register({
|
|
1068
|
+
provider: PO_CHILD_REPORT_WORK_PROVIDER,
|
|
1069
|
+
listActiveWork: () => childGate.holding ? [{
|
|
1070
|
+
id: `terminal-report:${options.sessionId}`,
|
|
1071
|
+
sessionId: options.sessionId,
|
|
1072
|
+
label: "Reporting to parent"
|
|
1073
|
+
}] : []
|
|
1074
|
+
});
|
|
1075
|
+
const settledGate = agent.registerHook(defineHook({
|
|
1076
|
+
name: "session-check-child-terminal-report",
|
|
1077
|
+
description: "Update the session snapshot and check whether the child can report completion to its parent.",
|
|
1078
|
+
event: "agent_settled",
|
|
1079
|
+
handle: (event, execution) => {
|
|
1080
|
+
session = execution.session;
|
|
1081
|
+
childGate.settled(event).catch(notice("Child report check failed"));
|
|
1082
|
+
}
|
|
1083
|
+
}));
|
|
1084
|
+
childGate.start().catch(notice("Child report check failed"));
|
|
1085
|
+
releases.push(() => {
|
|
1086
|
+
settledGate.dispose();
|
|
1087
|
+
childGate.close();
|
|
1088
|
+
handle?.dispose();
|
|
1089
|
+
if (gate === childGate) gate = void 0;
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
return () => {
|
|
1093
|
+
for (const release of releases.reverse()) release();
|
|
1094
|
+
if (ledger === resolved) ledger = void 0;
|
|
1095
|
+
};
|
|
96
1096
|
});
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
1097
|
+
const injection = owner.inject([PO_CODEMODE_SERVICE], (context) => {
|
|
1098
|
+
const codemode = readPoCodemode(context);
|
|
1099
|
+
const registration = codemode?.register("@agimon-ai/po-session", createSessionsNamespace(options));
|
|
1100
|
+
const network = codemode?.register("@agimon-ai/po-session", createNetworkNamespace({
|
|
1101
|
+
...networkOptions,
|
|
1102
|
+
translate: (key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read(), key, fallback, vars) ?? formatMessage(fallback, vars)
|
|
1103
|
+
}));
|
|
1104
|
+
const restriction = registration ? agent.registerToolRestriction({ excludedTools: [START_SESSION_TOOL_NAME, ...options.operations.fallbackToolName ? [options.operations.fallbackToolName] : []] }) : void 0;
|
|
1105
|
+
return () => {
|
|
1106
|
+
restriction?.dispose();
|
|
1107
|
+
network?.dispose();
|
|
1108
|
+
registration?.dispose();
|
|
1109
|
+
};
|
|
1110
|
+
});
|
|
1111
|
+
return async () => {
|
|
1112
|
+
await injection.dispose();
|
|
1113
|
+
await reporting.dispose();
|
|
1114
|
+
eligibility?.dispose();
|
|
1115
|
+
settled.dispose();
|
|
1116
|
+
stop.close();
|
|
1117
|
+
tool.dispose();
|
|
1118
|
+
};
|
|
1119
|
+
},
|
|
1120
|
+
(owner) => {
|
|
1121
|
+
owner.inject([
|
|
1122
|
+
PO_SESSION_PEERS_SERVICE,
|
|
1123
|
+
PO_SESSION_GROUP_BRIDGE_SERVICE,
|
|
1124
|
+
PO_FS_SERVICE,
|
|
1125
|
+
PO_SQLITE_SERVICE
|
|
1126
|
+
], async (context) => {
|
|
1127
|
+
const agent = pluginContext.agent;
|
|
1128
|
+
const session = agent?.context.session;
|
|
1129
|
+
const communication = pluginContext.host.context.sessionCommunication;
|
|
1130
|
+
const homeDirectory = pluginContext.host.context.homeDirectory;
|
|
1131
|
+
const sessionService = pluginContext.host.context.sessionService;
|
|
1132
|
+
if (!agent || !session?.admitPrompt || !communication || !homeDirectory || !sessionService?.canCommunicate) throw new Error("Session delivery requires the headless agent, authenticated session communication, host home directory, and communication policy.");
|
|
1133
|
+
const fs = requirePoFs(context);
|
|
1134
|
+
const sqlite = requirePoSqlite(context);
|
|
1135
|
+
const io = BACKGROUND_CONTEXT;
|
|
1136
|
+
const sessionDirectory = path.join(poHomeDirectory(homeDirectory, pluginContext.host.context.environment ?? {}), "session");
|
|
1137
|
+
const deliveryDirectory = path.join(sessionDirectory, "delivery");
|
|
1138
|
+
await ensurePrivateDirectory(fs, deliveryDirectory, io);
|
|
1139
|
+
const peers = requireSessionPeers(context);
|
|
1140
|
+
const peerConfig = peers.current();
|
|
1141
|
+
const peerCommunication = createPeerCommunication({
|
|
1142
|
+
local: communication,
|
|
1143
|
+
config: () => peers.current(),
|
|
1144
|
+
canPublish: (target, type, payload) => {
|
|
1145
|
+
if (type === "po/session-delivery/ack") return true;
|
|
1146
|
+
const metadata = payload?.metadata;
|
|
1147
|
+
return bridge?.peersFor(agent.context.sessionId).some((peer) => peer.sessionId === target && peer.sharedGroups.some((name) => namedSessionGroupId(name) === metadata?.groupId)) === true;
|
|
1148
|
+
},
|
|
1149
|
+
onError: (error) => pluginContext.host.context.onNotice(`Peer delivery failed: ${String(error)}`)
|
|
1150
|
+
});
|
|
1151
|
+
const remotePeerIsGranted = (peerKey) => {
|
|
1152
|
+
const peer = parseRemoteSessionReference(peerKey);
|
|
1153
|
+
return peer !== void 0 && peers.current()?.peers.some((candidate) => candidate.hostId === peer.hostId && candidate.allowedSessionIds.includes(agent.context.sessionId)) === true;
|
|
1154
|
+
};
|
|
1155
|
+
const fallbackAuthorization = (peerKey) => sessionService.canCommunicate?.(agent.context.sessionId, peerKey) === true || remotePeerIsGranted(peerKey);
|
|
1156
|
+
const bridge = readSessionGroupBridge(context);
|
|
1157
|
+
const groups = bridge?.groups;
|
|
1158
|
+
await bridge?.updateLocal(agent.context.sessionId, communication.sessionName ?? agent.context.sessionId, communication.groups ?? []);
|
|
1159
|
+
const localHostId = peerConfig?.hostId;
|
|
1160
|
+
const selfReference = localHostId ? peerSessionReference(localHostId, agent.context.sessionId) : void 0;
|
|
1161
|
+
const groupAuthorization = groups && selfReference && localHostId ? createSessionGroupDeliveryAuthorizer({
|
|
1162
|
+
selfReference,
|
|
1163
|
+
groups,
|
|
1164
|
+
peerReference: (peerKey) => parseRemoteSessionReference(peerKey) === void 0 ? peerSessionReference(localHostId, peerKey) : peerKey,
|
|
1165
|
+
fallback: fallbackAuthorization
|
|
1166
|
+
}) : void 0;
|
|
1167
|
+
const authorizePeer = (peerKey, metadata) => {
|
|
1168
|
+
if (metadata?.logbook !== void 0) {
|
|
1169
|
+
const peer = communication.describePeer?.(peerKey);
|
|
1170
|
+
if (peer?.coordinator !== true && peer?.coordinated !== true) return false;
|
|
1171
|
+
}
|
|
1172
|
+
const remote = parseRemoteSessionReference(peerKey);
|
|
1173
|
+
if (remote && !peers.current()?.peers.some((peer) => peer.hostId === remote.hostId)) return false;
|
|
1174
|
+
if (remote) {
|
|
1175
|
+
if (!bridge?.metadataFor(agent.context.sessionId, peerKey) || !metadata?.groupId || !bridge?.peersFor(agent.context.sessionId).find((peer) => peer.sessionId === peerKey)?.sharedGroups.some((name) => namedSessionGroupId(name) === metadata.groupId)) return false;
|
|
1176
|
+
return groupAuthorization ? groupAuthorization(peerKey, metadata) : false;
|
|
1177
|
+
}
|
|
1178
|
+
return groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey);
|
|
1179
|
+
};
|
|
1180
|
+
/** What this session was working on, so a peer's message ends by pointing back at it. */
|
|
1181
|
+
const workAnchor = () => {
|
|
1182
|
+
const work = (readPoContextContributions(context)?.snapshot().entries ?? []).map((entry) => entry.text).join("\n").slice(0, WORK_ANCHOR_MAX).trim();
|
|
1183
|
+
return work === "" ? "" : `\n\nBack to your work:\n${work}`;
|
|
1184
|
+
};
|
|
1185
|
+
/** How the chat shows a digest this session receives, under the name of what gathered it. */
|
|
1186
|
+
const digestMetadata = (name) => (prompt, deliveryId) => ({
|
|
1187
|
+
customType: INTERCOM_MESSAGE_TYPE,
|
|
1188
|
+
customDetails: JSON.stringify(intercomDetails("send", name, agent.context.sessionId, prompt, deliveryId))
|
|
1189
|
+
});
|
|
1190
|
+
let digest;
|
|
1191
|
+
let logbookWake;
|
|
1192
|
+
let delivery;
|
|
1193
|
+
try {
|
|
1194
|
+
delivery = await provideSessionDeliveryService(context, {
|
|
1195
|
+
database: await sqlite.open(path.join(deliveryDirectory, `${agent.context.sessionId}.sqlite`), io),
|
|
1196
|
+
recipientKey: agent.context.sessionId,
|
|
1197
|
+
communication: peerCommunication,
|
|
1198
|
+
authorizePeer,
|
|
1199
|
+
admitPrompt: async (prompt, admission, requestId, metadata) => {
|
|
1200
|
+
if (metadata.logbook !== void 0) {
|
|
1201
|
+
if (metadata.logbook === "blocked" || metadata.logbook === "settled") logbookWake?.note();
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
if (metadata.lane === "queue") {
|
|
1205
|
+
digest?.note();
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
if (!metadata.customType) {
|
|
1209
|
+
await session.admitPrompt(prompt, admission, void 0, requestId);
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
if (!session.admitMessage) throw new Error("The session cannot admit a custom delivery.");
|
|
1213
|
+
await session.admitMessage({
|
|
1214
|
+
type: metadata.customType,
|
|
1215
|
+
text: prompt + workAnchor(),
|
|
1216
|
+
display: true,
|
|
1217
|
+
details: metadata.customDetails === void 0 ? void 0 : JSON.parse(metadata.customDetails)
|
|
1218
|
+
}, admission === "steer" ? "steer" : "followUp", requestId);
|
|
1219
|
+
},
|
|
1220
|
+
onUndeliverable: (entry, error) => {
|
|
1221
|
+
pluginContext.host.context.onNotice(`Session delivery ${entry.kind} from ${entry.senderKey} was not admitted: ${error instanceof Error ? error.message : String(error)}`);
|
|
1222
|
+
if (entry.kind === "session-undelivered" || entry.metadata.logbook !== void 0) return;
|
|
1223
|
+
const group = bridge?.metadataFor(agent.context.sessionId, entry.senderKey);
|
|
1224
|
+
delivery.service.deliver(undeliveredNotice(entry, communication.sessionName ?? agent.context.sessionId, group?.sourceReference ?? agent.context.sessionId, group)).catch((failure) => pluginContext.host.context.onNotice(`Undelivered notice failed: ${String(failure)}`));
|
|
1225
|
+
},
|
|
1226
|
+
onError: (error) => pluginContext.host.context.onNotice(`Session delivery failed: ${String(error)}`)
|
|
1227
|
+
});
|
|
1228
|
+
} catch (error) {
|
|
1229
|
+
await bridge?.removeLocal(agent.context.sessionId);
|
|
1230
|
+
throw error;
|
|
1231
|
+
}
|
|
1232
|
+
const { service, close: closeDelivery } = delivery;
|
|
1233
|
+
const inbox = createInboxDigest({
|
|
1234
|
+
delayMs: INBOX_DIGEST_DELAY_MS,
|
|
1235
|
+
delivery: service,
|
|
1236
|
+
sessionId: agent.context.sessionId,
|
|
1237
|
+
idle: async () => (await session.activity()).isIdle,
|
|
1238
|
+
authorized: (entry) => authorizePeer(entry.senderKey, entry.metadata),
|
|
1239
|
+
metadata: digestMetadata("Inbox"),
|
|
1240
|
+
onError: (error) => pluginContext.host.context.onNotice(`Inbox digest failed: ${String(error)}`)
|
|
1241
|
+
});
|
|
1242
|
+
digest = inbox;
|
|
1243
|
+
const settledInbox = agent.registerHook(defineHook({
|
|
1244
|
+
name: "session-schedule-inbox-digest",
|
|
1245
|
+
description: "Schedule an inbox digest after a settled run unless the person aborted it.",
|
|
1246
|
+
event: "agent_settled",
|
|
1247
|
+
handle: async (event) => {
|
|
1248
|
+
if (event.aborted !== true) await inbox.settled();
|
|
1249
|
+
}
|
|
1250
|
+
}));
|
|
1251
|
+
const compacted = agent.registerHook(defineHook({
|
|
1252
|
+
name: "session-expire-mention-grants",
|
|
1253
|
+
description: "Expire session mention grants and reauthorize delivery after compaction completes.",
|
|
1254
|
+
event: "session_compact",
|
|
1255
|
+
handle: (event) => {
|
|
1256
|
+
if (event.status !== "completed") return;
|
|
1257
|
+
sessionService.mentions?.expire(agent.context.sessionId);
|
|
1258
|
+
service.reauthorize?.().catch((error) => pluginContext.host.context.onNotice(`Delivery reauthorization failed: ${String(error)}`));
|
|
1259
|
+
}
|
|
1260
|
+
}));
|
|
1261
|
+
inbox.note();
|
|
1262
|
+
await rearmAskReminders(service, (text, requestId, details) => remindSession(agent, text, requestId, details), (error) => pluginContext.host.context.onNotice(`Ask reminder failed: ${String(error)}`));
|
|
1263
|
+
logbookWake = createLogbookWake({
|
|
1264
|
+
delayMs: LOGBOOK_WAKE_DELAY_MS,
|
|
1265
|
+
delivery: service,
|
|
1266
|
+
sessionId: agent.context.sessionId,
|
|
1267
|
+
peer: (sessionId) => communication.describePeer?.(sessionId),
|
|
1268
|
+
metadata: digestMetadata("Logbook"),
|
|
1269
|
+
onError: (error) => pluginContext.host.context.onNotice(`Logbook wake failed: ${String(error)}`)
|
|
1270
|
+
});
|
|
1271
|
+
logbookWake.note();
|
|
1272
|
+
const unprovide = [];
|
|
1273
|
+
if (groups && selfReference && peerConfig) {
|
|
1274
|
+
const directory = createSessionDirectory({ authorizeDiscovery: (_caller, subject) => {
|
|
1275
|
+
const reference = peerSessionReference(subject.hostId, subject.sessionId);
|
|
1276
|
+
return bridge?.peersFor(agent.context.sessionId).some((peer) => peer.sessionId === reference) ? { capabilities: ["message"] } : void 0;
|
|
1277
|
+
} });
|
|
1278
|
+
const observedHosts = /* @__PURE__ */ new Set();
|
|
1279
|
+
let sequence = 0;
|
|
1280
|
+
const observeRemote = () => {
|
|
1281
|
+
const remotePeers = bridge?.peersFor(agent.context.sessionId) ?? [];
|
|
1282
|
+
for (const peer of remotePeers) observedHosts.add(parseRemoteSessionReference(peer.sessionId).hostId);
|
|
1283
|
+
sequence += 1;
|
|
1284
|
+
for (const hostId of observedHosts) directory.replaceHostSnapshot(hostId, "linked", remotePeers.flatMap((peer) => {
|
|
1285
|
+
const remote = parseRemoteSessionReference(peer.sessionId);
|
|
1286
|
+
return remote.hostId !== hostId ? [] : [{
|
|
1287
|
+
hostId,
|
|
1288
|
+
sessionId: remote.sessionId,
|
|
1289
|
+
label: peer.name,
|
|
1290
|
+
hostIncarnation: "linked",
|
|
1291
|
+
sessionIncarnation: "live",
|
|
1292
|
+
sequence,
|
|
1293
|
+
observedAt: Date.now(),
|
|
1294
|
+
staleAfterMs: 12e4,
|
|
1295
|
+
deliveryTarget: peer.sessionId,
|
|
1296
|
+
reachability: "unknown",
|
|
1297
|
+
runtime: "unknown",
|
|
1298
|
+
activity: "unknown",
|
|
1299
|
+
voice: {
|
|
1300
|
+
eligible: "unknown",
|
|
1301
|
+
readiness: "unknown"
|
|
1302
|
+
}
|
|
1303
|
+
}];
|
|
1304
|
+
}));
|
|
1305
|
+
};
|
|
1306
|
+
observeRemote();
|
|
1307
|
+
unprovide.push(bridge.subscribe(() => {
|
|
1308
|
+
observeRemote();
|
|
1309
|
+
service.reauthorize?.().catch((error) => pluginContext.host.context.onNotice(`Delivery reauthorization failed: ${String(error)}`));
|
|
1310
|
+
}));
|
|
1311
|
+
unprovide.push(context.provide(PO_SESSION_INTERCOM_SERVICE, createSessionIntercom({
|
|
1312
|
+
selfReference,
|
|
1313
|
+
directory,
|
|
1314
|
+
groups,
|
|
1315
|
+
delivery: service
|
|
1316
|
+
})));
|
|
1317
|
+
}
|
|
1318
|
+
const releaseGroups = pluginContext.host.context.directEvents?.subscribe(PO_SESSION_ATTENTION_EVENT, agent.context.sessionId, () => {
|
|
1319
|
+
bridge?.updateLocal(agent.context.sessionId, communication.sessionName ?? agent.context.sessionId, communication.groups ?? []).catch((error) => pluginContext.host.context.onNotice(`Group update failed: ${String(error)}`));
|
|
1320
|
+
});
|
|
1321
|
+
const unregister = registerSessionPeerInbox(agent.context.sessionId, (sourceKey, kind, payload) => service.receive?.(sourceKey, kind, payload));
|
|
1322
|
+
return async () => {
|
|
1323
|
+
unregister();
|
|
1324
|
+
settledInbox.dispose();
|
|
1325
|
+
compacted.dispose();
|
|
1326
|
+
inbox.close();
|
|
1327
|
+
logbookWake?.close();
|
|
1328
|
+
releaseGroups?.();
|
|
1329
|
+
await bridge?.removeLocal(agent.context.sessionId);
|
|
1330
|
+
for (const release of unprovide.reverse()) release();
|
|
1331
|
+
await closeDelivery();
|
|
1332
|
+
};
|
|
1333
|
+
});
|
|
1334
|
+
},
|
|
1335
|
+
(owner) => {
|
|
1336
|
+
const sessionId = pluginContext.host.context.sessionId;
|
|
1337
|
+
if (sessionId === void 0) return;
|
|
1338
|
+
const lifetime = new AbortController();
|
|
1339
|
+
const binding = owner.inject([PO_SERVER_SCOPE_SERVICE], async (context) => {
|
|
1340
|
+
const scope = requirePoServerScope(context);
|
|
1341
|
+
const service = createAgentRunService({
|
|
1342
|
+
sessionId,
|
|
1343
|
+
cwd: pluginContext.host.context.cwd,
|
|
1344
|
+
sessions: pluginContext.host.context.sessionService,
|
|
1345
|
+
approvals: () => scope.resolve(APPROVAL_ROOT_SERVICE),
|
|
1346
|
+
lifetime: lifetime.signal,
|
|
1347
|
+
onError: (error) => pluginContext.host.context.onNotice(`Agent run cleanup failed: ${String(error)}`)
|
|
1348
|
+
});
|
|
1349
|
+
return await scope.provide(PO_AGENT_RUN_CONTRACT, service);
|
|
1350
|
+
});
|
|
1351
|
+
return async () => {
|
|
1352
|
+
lifetime.abort(/* @__PURE__ */ new Error("The session that started this agent run closed."));
|
|
1353
|
+
await binding.dispose();
|
|
1354
|
+
};
|
|
103
1355
|
}
|
|
104
|
-
|
|
105
|
-
return async () => {
|
|
106
|
-
unregister();
|
|
107
|
-
for (const release of unprovide.reverse()) release();
|
|
108
|
-
await closeDelivery();
|
|
109
|
-
await groups?.close();
|
|
110
|
-
};
|
|
111
|
-
}]
|
|
1356
|
+
]
|
|
112
1357
|
}));
|
|
113
1358
|
//#endregion
|
|
1359
|
+
//#region src/extensions/workspaces/sessions/(backend)/contract/agentRun.server.ts
|
|
1360
|
+
var agentRun_server_default = defineServiceContract(PO_AGENT_RUN_CONTRACT.name, PO_AGENT_RUN_CONTRACT);
|
|
1361
|
+
//#endregion
|
|
114
1362
|
//#region src/services/peerInboxApi/index.ts
|
|
115
1363
|
const MAX_BODY_BYTES = 65536;
|
|
116
1364
|
const DELIVERY_TYPES = /* @__PURE__ */ new Set(["po/session-delivery/envelope", "po/session-delivery/ack"]);
|
|
@@ -123,32 +1371,124 @@ function createPeerInboxApi(platform) {
|
|
|
123
1371
|
basePath: "session-peer",
|
|
124
1372
|
start(context) {
|
|
125
1373
|
const homeDirectory = context.homeDirectory;
|
|
1374
|
+
const environment = context.environment ?? {};
|
|
126
1375
|
let opened;
|
|
1376
|
+
const channels = createSealedPeerChannels();
|
|
1377
|
+
let link;
|
|
1378
|
+
let announcing = false;
|
|
1379
|
+
const announce = () => {
|
|
1380
|
+
if (!link || announcing) return;
|
|
1381
|
+
announcing = true;
|
|
1382
|
+
link.announce().catch((error) => context.onNotice(`Peer URL announcement failed: ${String(error)}`)).finally(() => {
|
|
1383
|
+
announcing = false;
|
|
1384
|
+
});
|
|
1385
|
+
};
|
|
1386
|
+
let linking = false;
|
|
1387
|
+
const autoLink = () => {
|
|
1388
|
+
if (!link || linking) return;
|
|
1389
|
+
linking = true;
|
|
1390
|
+
link.auto().catch((error) => context.onNotice(`Automatic host link failed: ${String(error)}`)).finally(() => {
|
|
1391
|
+
linking = false;
|
|
1392
|
+
});
|
|
1393
|
+
};
|
|
1394
|
+
const timer = platform.peers && platform.origin ? setInterval(() => {
|
|
1395
|
+
open().then(announce).catch((error) => context.onNotice(`Host links could not start: ${String(error)}`));
|
|
1396
|
+
}, 1e3) : void 0;
|
|
1397
|
+
timer?.unref?.();
|
|
1398
|
+
const autoTimer = platform.peers && platform.origin && platform.hosts ? setInterval(() => {
|
|
1399
|
+
open().then(autoLink).catch((error) => context.onNotice(`Host links could not start: ${String(error)}`));
|
|
1400
|
+
}, 6e4) : void 0;
|
|
1401
|
+
autoTimer?.unref?.();
|
|
127
1402
|
const open = () => opened ??= (async () => {
|
|
128
1403
|
if (homeDirectory === void 0) return {
|
|
129
1404
|
config: void 0,
|
|
130
1405
|
replay: void 0
|
|
131
1406
|
};
|
|
132
|
-
const config = await readSessionPeerConfigAsync(platform.fs, homeDirectory, BACKGROUND_CONTEXT);
|
|
133
|
-
const file = path.join(path.dirname(sessionPeerConfigPath(homeDirectory)), PEER_REPLAY_DATABASE_FILE);
|
|
1407
|
+
const config = platform.peers ? platform.peers.current() : await readSessionPeerConfigAsync(platform.fs, homeDirectory, BACKGROUND_CONTEXT, environment);
|
|
1408
|
+
const file = path.join(path.dirname(sessionPeerConfigPath(homeDirectory, environment)), PEER_REPLAY_DATABASE_FILE);
|
|
134
1409
|
await ensurePrivateDirectory(platform.fs, path.dirname(file), BACKGROUND_CONTEXT);
|
|
1410
|
+
const replay = await createPeerReplayGuardAsync(await platform.sqlite.open(file, BACKGROUND_CONTEXT));
|
|
1411
|
+
if (platform.peers) link = createPeerLink({
|
|
1412
|
+
peers: platform.peers,
|
|
1413
|
+
network: platform.network,
|
|
1414
|
+
hosts: platform.hosts,
|
|
1415
|
+
groups: platform.groups,
|
|
1416
|
+
replay,
|
|
1417
|
+
channels,
|
|
1418
|
+
origin: platform.origin ?? (() => void 0),
|
|
1419
|
+
fetch: platform.fetch
|
|
1420
|
+
});
|
|
1421
|
+
announce();
|
|
1422
|
+
autoLink();
|
|
135
1423
|
return {
|
|
136
1424
|
config,
|
|
137
|
-
replay
|
|
1425
|
+
replay
|
|
138
1426
|
};
|
|
139
1427
|
})().catch((error) => {
|
|
140
1428
|
opened = void 0;
|
|
141
1429
|
throw error;
|
|
142
1430
|
});
|
|
1431
|
+
if (platform.peers) open().catch((error) => context.onNotice(`Host links could not start: ${String(error)}`));
|
|
143
1432
|
return {
|
|
144
1433
|
async fetch(request) {
|
|
145
|
-
|
|
146
|
-
const
|
|
147
|
-
|
|
1434
|
+
const pathname = new URL(request.url).pathname;
|
|
1435
|
+
const openedState = await open();
|
|
1436
|
+
const config = platform.peers ? platform.peers.current() : openedState.config;
|
|
1437
|
+
const replay = openedState.replay;
|
|
1438
|
+
if (request.method === "GET" && pathname === "/links" && platform.peers) {
|
|
1439
|
+
if (!poApiCallerFrom(request.headers)) return response(403, "An authenticated caller is required.");
|
|
1440
|
+
return Response.json({
|
|
1441
|
+
hostId: config?.hostId,
|
|
1442
|
+
peers: config?.peers.map(({ hostId, url, urlGeneration }) => ({
|
|
1443
|
+
hostId,
|
|
1444
|
+
url,
|
|
1445
|
+
urlGeneration
|
|
1446
|
+
})) ?? []
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
if (request.method !== "POST" || ![
|
|
1450
|
+
"/inbox",
|
|
1451
|
+
"/control",
|
|
1452
|
+
"/link/prepare",
|
|
1453
|
+
"/link/accept",
|
|
1454
|
+
"/link/unlink",
|
|
1455
|
+
"/link/hint"
|
|
1456
|
+
].includes(pathname)) return response(404, "Not found.");
|
|
148
1457
|
const length = request.headers.get("content-length");
|
|
149
1458
|
if (length !== null && (!/^\d+$/u.test(length) || Number(length) > MAX_BODY_BYTES)) return response(413, "Request body is too large.");
|
|
150
1459
|
const body = await request.text();
|
|
151
1460
|
if (Buffer.byteLength(body) > MAX_BODY_BYTES) return response(413, "Request body is too large.");
|
|
1461
|
+
if (pathname.startsWith("/link/")) {
|
|
1462
|
+
const caller = poApiCallerFrom(request.headers);
|
|
1463
|
+
if (!caller || caller.locality === "remote" && pathname !== "/link/hint" && caller.stepUp !== "verified") return response(403, "Linking hosts needs a fresh peer.link step-up.");
|
|
1464
|
+
if (!link) return response(503, "Host links are unavailable.");
|
|
1465
|
+
try {
|
|
1466
|
+
const input = body === "" ? {} : JSON.parse(body);
|
|
1467
|
+
if (pathname === "/link/prepare") return Response.json(await link.prepare());
|
|
1468
|
+
if (pathname === "/link/accept") {
|
|
1469
|
+
await link.accept(input.invite);
|
|
1470
|
+
return Response.json({ linked: true });
|
|
1471
|
+
}
|
|
1472
|
+
if (typeof input.hostId !== "string") return response(400, "A host identity is required.");
|
|
1473
|
+
if (pathname === "/link/unlink") {
|
|
1474
|
+
await link.unlink(input.hostId);
|
|
1475
|
+
return Response.json({ unlinked: true });
|
|
1476
|
+
}
|
|
1477
|
+
if (typeof input.url !== "string") return response(400, "A URL hint is required.");
|
|
1478
|
+
return Response.json({ rebound: await link.hint(input.hostId, input.url) });
|
|
1479
|
+
} catch (error) {
|
|
1480
|
+
return response(400, error instanceof Error ? error.message : "Host link failed.");
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
if (pathname === "/control") {
|
|
1484
|
+
if (!link) return response(503, "Host links are unavailable.");
|
|
1485
|
+
try {
|
|
1486
|
+
return await link.control(request, body);
|
|
1487
|
+
} catch (error) {
|
|
1488
|
+
return response(400, error instanceof Error ? error.message : "Invalid peer control.");
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
if (!config) return response(503, "Paired Session delivery is not configured.");
|
|
152
1492
|
const peer = verifyPeerRequest(config, request, body);
|
|
153
1493
|
if (!peer) return response(401, "Paired Session request is unauthorized.");
|
|
154
1494
|
if (!await replay?.admit(request)) return response(409, "Paired Session request was already received.");
|
|
@@ -158,17 +1498,42 @@ function createPeerInboxApi(platform) {
|
|
|
158
1498
|
} catch {
|
|
159
1499
|
return response(400, "Paired Session request is malformed.");
|
|
160
1500
|
}
|
|
1501
|
+
let peerChannel;
|
|
1502
|
+
if (peer.linkGeneration) {
|
|
1503
|
+
const sealed = parsed;
|
|
1504
|
+
peerChannel = typeof sealed?.epochId === "string" ? channels.take(peer, sealed.epochId) : void 0;
|
|
1505
|
+
const opened = peerChannel?.open(sealed?.envelope);
|
|
1506
|
+
if (!opened?.ok) return response(401, "A fresh sealed peer channel is required.");
|
|
1507
|
+
try {
|
|
1508
|
+
parsed = JSON.parse(Buffer.from(opened.plaintext).toString("utf8"));
|
|
1509
|
+
} catch {
|
|
1510
|
+
return response(400, "Invalid sealed peer envelope.");
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
161
1513
|
const envelope = parseSessionPeerEnvelope(parsed);
|
|
162
1514
|
if (!envelope || !DELIVERY_TYPES.has(envelope.type)) return response(400, "Paired Session envelope is invalid.");
|
|
163
|
-
if (!peer.allowedSessionIds.includes(envelope.targetSessionId)) return response(403, "Peer is not granted this session.");
|
|
1515
|
+
if (!peer.linkGeneration && !peer.allowedSessionIds.includes(envelope.targetSessionId)) return response(403, "Peer is not granted this session.");
|
|
164
1516
|
const state = await deliverSessionPeerEnvelope(envelope.targetSessionId, peerSessionReference(peer.hostId, envelope.sourceSessionId), envelope.type, envelope.payload);
|
|
1517
|
+
if (state !== void 0 && peerChannel) {
|
|
1518
|
+
const sealed = peerChannel.seal(Buffer.from(JSON.stringify({
|
|
1519
|
+
accepted: true,
|
|
1520
|
+
state
|
|
1521
|
+
})));
|
|
1522
|
+
if (!sealed.ok) return response(503, "Peer acknowledgement could not be sealed.");
|
|
1523
|
+
const text = JSON.stringify(sealed.envelope);
|
|
1524
|
+
return new Response(text, { headers: peerRequestHeaders(config.hostId, peer, "RESPONSE", "/inbox", text) });
|
|
1525
|
+
}
|
|
165
1526
|
return state === void 0 ? response(404, "Target Session is unavailable.") : Response.json({
|
|
166
1527
|
accepted: true,
|
|
167
1528
|
state
|
|
168
1529
|
}, { status: 202 });
|
|
169
1530
|
},
|
|
170
1531
|
async close() {
|
|
171
|
-
|
|
1532
|
+
if (timer) clearInterval(timer);
|
|
1533
|
+
if (autoTimer) clearInterval(autoTimer);
|
|
1534
|
+
const state = await opened?.catch(() => void 0);
|
|
1535
|
+
link?.close();
|
|
1536
|
+
await state?.replay?.close();
|
|
172
1537
|
}
|
|
173
1538
|
};
|
|
174
1539
|
}
|
|
@@ -176,33 +1541,216 @@ function createPeerInboxApi(platform) {
|
|
|
176
1541
|
}
|
|
177
1542
|
//#endregion
|
|
178
1543
|
//#region src/extensions/(backend)/api/session-peer/route.server.ts
|
|
179
|
-
var route_server_default = defineRoute(({ context }) =>
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
1544
|
+
var route_server_default = defineRoute(({ context }) => {
|
|
1545
|
+
let origin;
|
|
1546
|
+
let network;
|
|
1547
|
+
let hosts;
|
|
1548
|
+
context.inject(["po/host-requests"], (scoped) => {
|
|
1549
|
+
hosts = scoped.get("po/host-requests");
|
|
1550
|
+
return () => {
|
|
1551
|
+
hosts = void 0;
|
|
1552
|
+
};
|
|
1553
|
+
});
|
|
1554
|
+
context.inject([PO_ROSTER_PEER_SERVICE], (scoped) => {
|
|
1555
|
+
network = scoped.get(PO_ROSTER_PEER_SERVICE);
|
|
1556
|
+
return () => {
|
|
1557
|
+
network = void 0;
|
|
1558
|
+
};
|
|
1559
|
+
});
|
|
1560
|
+
context.inject([PO_REMOTE_ORIGIN_SERVICE], (scoped) => {
|
|
1561
|
+
origin = scoped.get(PO_REMOTE_ORIGIN_SERVICE);
|
|
1562
|
+
return () => {
|
|
1563
|
+
origin = void 0;
|
|
1564
|
+
};
|
|
1565
|
+
});
|
|
1566
|
+
const hasOrigin = origin !== void 0;
|
|
1567
|
+
return createPeerInboxApi({
|
|
1568
|
+
fs: requirePoFs(context),
|
|
1569
|
+
sqlite: requirePoSqlite(context),
|
|
1570
|
+
peers: requireSessionPeers(context),
|
|
1571
|
+
network,
|
|
1572
|
+
hosts: () => hosts,
|
|
1573
|
+
groups: () => readSessionGroupBridge(context),
|
|
1574
|
+
...hasOrigin ? { origin: () => origin?.current() } : {}
|
|
1575
|
+
});
|
|
1576
|
+
});
|
|
1577
|
+
//#endregion
|
|
1578
|
+
//#region src/schemas/sendToSession.ts
|
|
1579
|
+
/** The person's own words, steered into another live session and shown there as "From you, via <from>". */
|
|
1580
|
+
const sendToSessionMethod = definePoPluginMethod({
|
|
1581
|
+
service: "sessions",
|
|
1582
|
+
method: "sendToSession",
|
|
1583
|
+
scope: "host",
|
|
1584
|
+
direction: "client-to-server",
|
|
1585
|
+
input: Type.Object({
|
|
1586
|
+
/** The session whose composer the person typed in; it names the message, nothing more. */
|
|
1587
|
+
from: Type.String({ minLength: 1 }),
|
|
1588
|
+
to: Type.String({ minLength: 1 }),
|
|
1589
|
+
text: Type.String({
|
|
1590
|
+
minLength: 1,
|
|
1591
|
+
maxLength: 1e5
|
|
1592
|
+
})
|
|
1593
|
+
}, { additionalProperties: false }),
|
|
1594
|
+
output: Type.Object({
|
|
1595
|
+
to: Type.String(),
|
|
1596
|
+
name: Type.String()
|
|
1597
|
+
})
|
|
1598
|
+
});
|
|
1599
|
+
//#endregion
|
|
1600
|
+
//#region src/extensions/(backend)/_lib/sendToSession.server.ts
|
|
1601
|
+
/**
|
|
1602
|
+
* Steers the person's text into another live session, attributed to them. Each refusal reads as the
|
|
1603
|
+
* reason the dialog shows, because the text stays there for another try.
|
|
1604
|
+
*/
|
|
1605
|
+
async function sendToSession(service, input) {
|
|
1606
|
+
const text = input.text.trim();
|
|
1607
|
+
if (text === "") throw new Error("Write something to send.");
|
|
1608
|
+
if (input.to === input.from) throw new Error("That is this session. Pick another one.");
|
|
1609
|
+
if (!service?.steer || !service.scopes) throw new Error("This host cannot deliver to another session.");
|
|
1610
|
+
const scopes = service.scopes();
|
|
1611
|
+
const target = scopes.find((scope) => scope.sessionId === input.to);
|
|
1612
|
+
if (target === void 0) throw new Error("That session is not running. Open it to wake it, then send again.");
|
|
1613
|
+
const name = target.name?.trim() || input.to;
|
|
1614
|
+
const via = scopes.find((scope) => scope.sessionId === input.from)?.name?.trim() || "another session";
|
|
1615
|
+
try {
|
|
1616
|
+
await service.steer(input.to, {
|
|
1617
|
+
text,
|
|
1618
|
+
sender: {
|
|
1619
|
+
kind: "human",
|
|
1620
|
+
name: `From you, via ${via}`
|
|
1621
|
+
}
|
|
1622
|
+
});
|
|
1623
|
+
} catch (error) {
|
|
1624
|
+
throw new Error(`${name} could not take the message: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1625
|
+
}
|
|
1626
|
+
return {
|
|
1627
|
+
to: input.to,
|
|
1628
|
+
name
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
//#endregion
|
|
1632
|
+
//#region src/extensions/(backend)/method/send-to-session.server.ts
|
|
1633
|
+
var send_to_session_server_default = defineRoutedContribution(({ host }) => host.scope === "host" ? defineServerMethod(sendToSessionMethod, (input) => sendToSession(host.context.sessionService, input)) : void 0, { cardinality: "optional" });
|
|
1634
|
+
//#endregion
|
|
1635
|
+
//#region src/extensions/workspaces/sessions/(backend)/hook/before-agent-start.server.ts
|
|
1636
|
+
const BOT_AUTONOMY = `You are running as a bot session. Be proactive and work autonomously toward the person's goals. Make decisions yourself from the evidence and reasonable defaults; do not stop to ask whether to continue while useful, authorized work remains. When something fails, diagnose it and try bounded, reversible fixes before escalating. Ask the person only when you are blocked, when uncertainty is high enough that proceeding could cause harm or wasted work, or when explicit approval is required. When you ask, give the evidence, what you tried, and the exact decision needed, then keep doing unrelated authorized work while you wait. Never bypass approval or safety gates, and stop when the person says stop.`;
|
|
1637
|
+
var before_agent_start_server_default = defineHook({
|
|
1638
|
+
name: "bot-autonomy-guidance",
|
|
1639
|
+
description: "In bot sessions, append guidance to work autonomously and ask the person only on blockers or high uncertainty.",
|
|
1640
|
+
event: "before_agent_start",
|
|
1641
|
+
async handle({ systemPrompt }, execution) {
|
|
1642
|
+
if (await execution.isBotSession?.() !== true) return;
|
|
1643
|
+
return { systemPrompt: `${typeof systemPrompt === "string" ? systemPrompt : ""}\n\n${BOT_AUTONOMY}` };
|
|
1644
|
+
}
|
|
1645
|
+
});
|
|
1646
|
+
//#endregion
|
|
1647
|
+
//#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-network.server.ts
|
|
1648
|
+
var codemode_how_to_network_server_default = defineResource({
|
|
1649
|
+
name: "codemode-how-to-network",
|
|
1650
|
+
description: "Message sessions on this host and on linked hosts through the network namespace: send, ask with a tracked reply, and answer questions. Use for any message to another session.",
|
|
1651
|
+
kind: "skill",
|
|
1652
|
+
pinned: true,
|
|
1653
|
+
path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-network/SKILL.md"),
|
|
1654
|
+
read: () => readPackageResource(import.meta.url, "src/prompts/codemode-how-to-network/SKILL.md")
|
|
1655
|
+
});
|
|
1656
|
+
//#endregion
|
|
1657
|
+
//#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-session.server.ts
|
|
1658
|
+
var codemode_how_to_session_server_default = defineResource({
|
|
1659
|
+
name: "codemode-how-to-session",
|
|
1660
|
+
description: "List related sessions and start briefed independent work as a coordinator through the sessions namespace. No stop or delete capability.",
|
|
1661
|
+
kind: "skill",
|
|
1662
|
+
pinned: true,
|
|
1663
|
+
path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-session/SKILL.md"),
|
|
1664
|
+
read: () => readPackageResource(import.meta.url, "src/prompts/codemode-how-to-session/SKILL.md")
|
|
1665
|
+
});
|
|
183
1666
|
//#endregion
|
|
184
1667
|
//#region generated/server.ts
|
|
185
1668
|
const at = (value, context) => typeof value === "function" ? value(context) : value;
|
|
1669
|
+
/* v8 ignore next -- generated normalization branch */
|
|
1670
|
+
const defined = (values) => values.filter((value) => value !== void 0);
|
|
1671
|
+
const via = (identity, value) => {
|
|
1672
|
+
if (value === void 0) return void 0;
|
|
1673
|
+
const declaration = value;
|
|
1674
|
+
return {
|
|
1675
|
+
...identity,
|
|
1676
|
+
...declaration,
|
|
1677
|
+
...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
|
|
1678
|
+
evidence: "declared",
|
|
1679
|
+
...relation
|
|
1680
|
+
})) }
|
|
1681
|
+
};
|
|
1682
|
+
};
|
|
186
1683
|
const serverPlugin = defineServerPlugin({
|
|
187
1684
|
name: "@agimon-ai/po-session",
|
|
188
|
-
providerOverrides: composeServerProviderOverrides(root_server_default),
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
1685
|
+
providerOverrides: composeServerProviderOverrides(root_server_default$1, root_server_default),
|
|
1686
|
+
provides: { session: [agentRun_server_default] },
|
|
1687
|
+
injects: composeRootInjects({
|
|
1688
|
+
host: [root_server_default$1],
|
|
1689
|
+
workspace: [root_server_default$1],
|
|
1690
|
+
session: [root_server_default$1, root_server_default]
|
|
1691
|
+
}),
|
|
1692
|
+
host: async (context) => {
|
|
1693
|
+
const scopeHost = await context.scopeRoot("host", root_server_default$1, context);
|
|
1694
|
+
const contextHost = {
|
|
1695
|
+
...context,
|
|
1696
|
+
root: scopeHost.value
|
|
1697
|
+
};
|
|
1698
|
+
return {
|
|
1699
|
+
...composeRootHooks(scopeHost),
|
|
1700
|
+
get api() {
|
|
1701
|
+
return [at(route_server_default, contextHost)];
|
|
1702
|
+
},
|
|
1703
|
+
get methods() {
|
|
1704
|
+
return defined([at(send_to_session_server_default, contextHost)]);
|
|
1705
|
+
},
|
|
1706
|
+
services: [...scopeHost.services ?? []]
|
|
1707
|
+
};
|
|
1708
|
+
},
|
|
1709
|
+
workspace: async (context) => {
|
|
1710
|
+
const scopeHost = await context.scopeRoot("host", root_server_default$1, context);
|
|
1711
|
+
const contextHost = {
|
|
1712
|
+
...context,
|
|
1713
|
+
root: scopeHost.value
|
|
1714
|
+
};
|
|
1715
|
+
return {
|
|
1716
|
+
...composeRootHooks(scopeHost),
|
|
1717
|
+
get api() {
|
|
1718
|
+
return defined([context.hosted("host") ? void 0 : at(route_server_default, contextHost)]);
|
|
1719
|
+
},
|
|
1720
|
+
get methods() {
|
|
1721
|
+
return defined([context.hosted("host") ? void 0 : at(send_to_session_server_default, contextHost)]);
|
|
1722
|
+
},
|
|
1723
|
+
services: [...scopeHost.services ?? []]
|
|
1724
|
+
};
|
|
1725
|
+
},
|
|
196
1726
|
session: async (context) => {
|
|
197
|
-
const
|
|
1727
|
+
const scopeHost = await context.scopeRoot("host", root_server_default$1, context);
|
|
1728
|
+
const contextHost = {
|
|
1729
|
+
...context,
|
|
1730
|
+
root: scopeHost.value
|
|
1731
|
+
};
|
|
1732
|
+
const scopeSession = await context.scopeRoot("session", root_server_default, contextHost);
|
|
1733
|
+
const contextSession = {
|
|
1734
|
+
...contextHost,
|
|
1735
|
+
root: scopeSession.value
|
|
1736
|
+
};
|
|
198
1737
|
return {
|
|
199
|
-
...composeRootHooks(scopeSession),
|
|
1738
|
+
...composeRootHooks(scopeHost, scopeSession),
|
|
200
1739
|
get api() {
|
|
201
|
-
return [at(route_server_default,
|
|
1740
|
+
return defined([context.hosted("host") ? void 0 : at(route_server_default, contextHost)]);
|
|
1741
|
+
},
|
|
1742
|
+
get hooks() {
|
|
1743
|
+
return [via({ event: "before_agent_start" }, at(before_agent_start_server_default, contextSession))];
|
|
1744
|
+
},
|
|
1745
|
+
get methods() {
|
|
1746
|
+
return defined([context.hosted("host") ? void 0 : at(send_to_session_server_default, contextHost)]);
|
|
1747
|
+
},
|
|
1748
|
+
get resources() {
|
|
1749
|
+
return [at(codemode_how_to_network_server_default, contextSession), at(codemode_how_to_session_server_default, contextSession)];
|
|
202
1750
|
},
|
|
203
|
-
services: [...scopeSession.services ?? []],
|
|
1751
|
+
services: [...scopeHost.services ?? [], ...scopeSession.services ?? []],
|
|
204
1752
|
get activities() {
|
|
205
|
-
return [...scopeSession.activities ?? []];
|
|
1753
|
+
return [...scopeHost.activities ?? [], ...scopeSession.activities ?? []];
|
|
206
1754
|
}
|
|
207
1755
|
};
|
|
208
1756
|
}
|