@klarkxy/dsh-delegation 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ import { RpcResult as RpcResult$1 } from "@klarkxy/dsh-plugin-kit/contracts";
2
+ //#region src/contracts.d.ts
3
+ type RpcResult<T = unknown> = RpcResult$1<T>;
4
+ declare const PLUGIN_NAME = "@klarkxy/dsh-delegation";
5
+ declare const RPC_CHANNEL = "/dsh-delegation";
6
+ declare const DELEGATION_CLIENT_SERVICE = "dshDelegationClient";
7
+ /** Native delegation tools; Delegation Mode only helps presets that mount one. */
8
+ declare const DELEGATION_TOOLS: readonly ["subagent", "subagent_fork"];
9
+ interface DelegationSettings {
10
+ readonly revision: number;
11
+ /** Initial delegation flag for sessions created from now on. */
12
+ readonly defaultEnabled: boolean;
13
+ }
14
+ declare const defaultSettings: () => DelegationSettings;
15
+ type DelegationRole = 'coordinator' | 'executor';
16
+ interface DelegationSessionStatus {
17
+ readonly sessionId: string;
18
+ /** 'executor' for subagent threads: they never carry their own switch. */
19
+ readonly role: DelegationRole;
20
+ /** The session record's flag; false when the session has no record yet. */
21
+ readonly enabled: boolean;
22
+ /** The session record's revision; 0 when the session has no record yet. */
23
+ readonly revision: number;
24
+ /** No edit is allowed once the first turn starts, or while the session is cold. */
25
+ readonly locked: boolean;
26
+ /**
27
+ * Whether a live agent on this session sees a delegation tool; null when no
28
+ * agent is live, so a stale answer is never shown as unavailable.
29
+ */
30
+ readonly capable: boolean | null;
31
+ }
32
+ //#endregion
33
+ export { DELEGATION_CLIENT_SERVICE, DELEGATION_TOOLS, DelegationRole, DelegationSessionStatus, DelegationSettings, PLUGIN_NAME, RPC_CHANNEL, RpcResult, defaultSettings };
34
+ //# sourceMappingURL=contracts.d.ts.map
@@ -0,0 +1,14 @@
1
+ //#region src/contracts.ts
2
+ const PLUGIN_NAME = "@klarkxy/dsh-delegation";
3
+ const RPC_CHANNEL = "/dsh-delegation";
4
+ const DELEGATION_CLIENT_SERVICE = "dshDelegationClient";
5
+ /** Native delegation tools; Delegation Mode only helps presets that mount one. */
6
+ const DELEGATION_TOOLS = ["subagent", "subagent_fork"];
7
+ const defaultSettings = () => ({
8
+ revision: 0,
9
+ defaultEnabled: false
10
+ });
11
+ //#endregion
12
+ export { DELEGATION_CLIENT_SERVICE, DELEGATION_TOOLS, PLUGIN_NAME, RPC_CHANNEL, defaultSettings };
13
+
14
+ //# sourceMappingURL=contracts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contracts.js","names":[],"sources":["../src/contracts.ts"],"sourcesContent":["/** Browser-safe contracts. Shared RPC/result types stay on @klarkxy/dsh-plugin-kit. */\nimport type { RpcResult as SharedRpcResult } from '@klarkxy/dsh-plugin-kit/contracts'\nexport type RpcResult<T = unknown> = SharedRpcResult<T>\n\nexport const PLUGIN_NAME = '@klarkxy/dsh-delegation'\nexport const RPC_CHANNEL = '/dsh-delegation'\nexport const DELEGATION_CLIENT_SERVICE = 'dshDelegationClient'\n\n/** Native delegation tools; Delegation Mode only helps presets that mount one. */\nexport const DELEGATION_TOOLS = ['subagent', 'subagent_fork'] as const\n\nexport interface DelegationSettings {\n readonly revision: number\n /** Initial delegation flag for sessions created from now on. */\n readonly defaultEnabled: boolean\n}\n\nexport const defaultSettings = (): DelegationSettings => ({ revision: 0, defaultEnabled: false })\n\nexport type DelegationRole = 'coordinator' | 'executor'\n\nexport interface DelegationSessionStatus {\n readonly sessionId: string\n /** 'executor' for subagent threads: they never carry their own switch. */\n readonly role: DelegationRole\n /** The session record's flag; false when the session has no record yet. */\n readonly enabled: boolean\n /** The session record's revision; 0 when the session has no record yet. */\n readonly revision: number\n /** No edit is allowed once the first turn starts, or while the session is cold. */\n readonly locked: boolean\n /**\n * Whether a live agent on this session sees a delegation tool; null when no\n * agent is live, so a stale answer is never shown as unavailable.\n */\n readonly capable: boolean | null\n}\n"],"mappings":";AAIA,MAAa,cAAc;AAC3B,MAAa,cAAc;AAC3B,MAAa,4BAA4B;;AAGzC,MAAa,mBAAmB,CAAC,YAAY,eAAe;AAQ5D,MAAa,yBAA6C;CAAE,UAAU;CAAG,gBAAgB;AAAM"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,136 @@
1
+ import { DelegationSessionStatus, DelegationSettings, RpcResult } from "./contracts.js";
2
+ import { z } from "zod";
3
+ import { Context } from "@deepseek-ai/cordis";
4
+ //#region src/storage.d.ts
5
+ interface SessionDelegation {
6
+ readonly enabled: boolean;
7
+ readonly revision: number;
8
+ }
9
+ //#endregion
10
+ //#region src/policy.d.ts
11
+ interface DelegationSessionLike {
12
+ readonly id: string;
13
+ readonly header?: {
14
+ readonly parentSession?: unknown;
15
+ };
16
+ }
17
+ /** The per-assembly lookups the policy needs; callers inject the live stores. */
18
+ interface DelegationLookups {
19
+ /** Parsed per-session record; undefined means no record. */
20
+ record(sessionId: string): {
21
+ readonly enabled: boolean;
22
+ } | undefined;
23
+ session(sessionId: string): DelegationSessionLike | undefined;
24
+ /** Whether a tool name resolves in this assembly's scope. */
25
+ toolVisible(name: string, scope: unknown): boolean;
26
+ }
27
+ interface DelegationAssembleContext {
28
+ readonly agent?: {
29
+ readonly session: DelegationSessionLike;
30
+ };
31
+ readonly scope?: unknown;
32
+ }
33
+ /** Static system guidance. No per-step counters or progress belong in this text. */
34
+ declare function delegationSectionText(context: DelegationAssembleContext, lookups: DelegationLookups): string;
35
+ //#endregion
36
+ //#region src/service.d.ts
37
+ declare class DelegationError extends Error {
38
+ readonly code: string;
39
+ constructor(code: string, message: string);
40
+ }
41
+ interface DelegationTableLike<V> {
42
+ get(key: string): V | undefined;
43
+ put(key: string, value: V): Promise<void>;
44
+ }
45
+ interface DelegationAgentLike {
46
+ readonly id: string;
47
+ readonly session?: DelegationSessionLike;
48
+ /** Claims the host's idle phase; waking input waits until this task settles. */
49
+ runMaintenance?<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
50
+ }
51
+ /** Cold-session read handle from the host's session query engine. */
52
+ interface DelegationObservationLike {
53
+ readonly header?: unknown;
54
+ [Symbol.dispose](): void;
55
+ }
56
+ interface DelegationServiceDeps {
57
+ /** Parsed global settings row (one key: 'global'). */
58
+ readonly settings: DelegationTableLike<DelegationSettings>;
59
+ /** Parsed per-session rows (key: session id). */
60
+ readonly records: DelegationTableLike<SessionDelegation>;
61
+ readonly sessionStore?: {
62
+ get(id: string): DelegationSessionLike | undefined;
63
+ };
64
+ readonly agents?: {
65
+ get(id: string): DelegationAgentLike | undefined;
66
+ };
67
+ readonly tools?: {
68
+ get(name: string, scope?: unknown): unknown;
69
+ };
70
+ /** Durable turn-boundary projection, including inherited and resumed turns. */
71
+ readonly hasStarted?: (session: DelegationSessionLike) => boolean;
72
+ /** Reads persisted headers for sessions that are not live (cold sessions). */
73
+ readonly sessionQuery?: {
74
+ observeSession(id: string, options: {
75
+ signal?: AbortSignal;
76
+ projectionMode?: string;
77
+ }): Promise<DelegationObservationLike>;
78
+ };
79
+ }
80
+ /**
81
+ * In-process CAS over the two domain tables. Table `get` is synchronous, so a
82
+ * per-key promise chain serializes check-and-write: two concurrent updates can
83
+ * never both pass the revision check, and a caller only hears success after
84
+ * `put` resolves.
85
+ */
86
+ declare class DelegationService {
87
+ private readonly deps;
88
+ private readonly chains;
89
+ constructor(deps: DelegationServiceDeps);
90
+ private enqueue;
91
+ getSettings(): DelegationSettings;
92
+ updateSettings(defaultEnabled: boolean, expectedRevision: number): Promise<DelegationSettings>;
93
+ /** The parsed session row; undefined means no record (off, revision 0). */
94
+ record(sessionId: string): SessionDelegation | undefined;
95
+ private locked;
96
+ /**
97
+ * The session header: live sessions read the store snapshot; a cold session
98
+ * is resolved through the query engine and the observation is always
99
+ * disposed before returning. Unknown sessions throw `no-session`.
100
+ */
101
+ private requireHeader;
102
+ sessionStatus(sessionId: string, signal?: AbortSignal): Promise<DelegationSessionStatus>;
103
+ updateSession(sessionId: string, enabled: boolean, expectedRevision: number, signal?: AbortSignal): Promise<DelegationSessionStatus>;
104
+ /**
105
+ * `agent/created` seeding. Only a fresh ('startup') non-subagent session gets
106
+ * an initial row: a human fork inherits its parent's flag, every other new
107
+ * top-level session takes the current `defaultEnabled`. Resumed, cleared and
108
+ * compacted sessions keep whatever they already have — and stay off when
109
+ * they predate the plugin.
110
+ */
111
+ seedSession(agent: DelegationAgentLike, source: string): Promise<void>;
112
+ }
113
+ //#endregion
114
+ //#region src/prompts.d.ts
115
+ /**
116
+ * System prompt text for delegation mode. Kept literal (the section registers
117
+ * with `interpolate: false`), so no `{{variable}}` syntax may appear here.
118
+ */
119
+ /** Coordinator policy for a top-level session with delegation on. */
120
+ declare function coordinatorPrompt(tools: readonly string[]): string;
121
+ /** Executor policy for a subagent whose top-level session has delegation on. */
122
+ declare const EXECUTOR_PROMPT = "## Delegated task\n\nYou are a subagent carrying out a task delegated by a coordinating agent. Coordinator instructions that appear earlier in this conversation, for example ones inherited through a fork, do not apply to you.\n\n- Do the work yourself: read, search, edit, run commands, and verify as the task requires. Make concrete progress in the assigned files; do not stop at a design or a plan. Do not pass the task on to further subagents unless the brief asks for it or clearly independent parts justify running them in parallel.\n- Stay within the brief. If it is ambiguous, make a reasonable choice and state it; if you are blocked, stop and report what is missing.\n- Respect file ownership and agreed interfaces. Ask the coordinator before changing another worker's files or a shared contract.\n- Verify your result before reporting.\n- End with a concise report: the result, the files or locations changed, the evidence (commands run and their outcome), and unresolved issues. Do not paste full logs.";
123
+ //#endregion
124
+ //#region src/index.d.ts
125
+ declare const name = "@klarkxy/dsh-delegation";
126
+ declare const inject: readonly ["systemPrompt", "storageDomain", "sessions", "agents", "tools", "sessionQuery", "sessionProjections", "connection", "webServer"];
127
+ declare module '@deepseek-ai/cordis' {
128
+ interface Context {
129
+ delegation: DelegationService;
130
+ }
131
+ }
132
+ declare function handleRpc(service: DelegationService, endpoint: string, payload: unknown, signal: AbortSignal): Promise<RpcResult>;
133
+ declare function apply(ctx: Context): Promise<void>;
134
+ //#endregion
135
+ export { DelegationError, DelegationService, EXECUTOR_PROMPT, apply, coordinatorPrompt, delegationSectionText, handleRpc, inject, name };
136
+ //# sourceMappingURL=index.d.ts.map
package/lib/index.js ADDED
@@ -0,0 +1,418 @@
1
+ import { DELEGATION_TOOLS, PLUGIN_NAME, RPC_CHANNEL, defaultSettings } from "./contracts.js";
2
+ import { registerHostRpc } from "@klarkxy/dsh-plugin-kit/host-rpc";
3
+ import { defineDomain, domainTable } from "@deepseek-ai/dsh-storage-domain";
4
+ import { z } from "zod";
5
+ import { isSubagentSession } from "@klarkxy/dsh-plugin-kit/contracts";
6
+ //#region src/storage.ts
7
+ const SETTINGS_KEY = "global";
8
+ const settingsSchema = z.object({
9
+ revision: z.number().int().nonnegative(),
10
+ defaultEnabled: z.boolean()
11
+ }).strict();
12
+ const sessionSchema = z.object({
13
+ enabled: z.boolean(),
14
+ revision: z.number().int().min(1)
15
+ }).strict();
16
+ const settingsUpdateSchema = z.object({
17
+ defaultEnabled: z.boolean(),
18
+ expectedRevision: z.number().int().nonnegative()
19
+ }).strict();
20
+ const sessionStatusSchema = z.object({ sessionId: z.string().min(1) }).strict();
21
+ const sessionUpdateSchema = z.object({
22
+ sessionId: z.string().min(1),
23
+ enabled: z.boolean(),
24
+ expectedRevision: z.number().int().nonnegative()
25
+ }).strict();
26
+ const delegationDomain = defineDomain({
27
+ name: "dsh_delegation",
28
+ version: 1,
29
+ tables: {
30
+ settings: domainTable(settingsSchema),
31
+ sessions: domainTable(sessionSchema)
32
+ }
33
+ });
34
+ /** A missing or unreadable settings row reads as the shipped defaults. */
35
+ function parseSettings(value) {
36
+ const parsed = settingsSchema.safeParse(value);
37
+ if (!parsed.success) return defaultSettings();
38
+ return {
39
+ revision: parsed.data.revision,
40
+ defaultEnabled: parsed.data.defaultEnabled
41
+ };
42
+ }
43
+ /** A missing or unreadable session row reads as "no record": off, revision 0. */
44
+ function parseSession(value) {
45
+ const parsed = sessionSchema.safeParse(value);
46
+ if (!parsed.success) return void 0;
47
+ return {
48
+ enabled: parsed.data.enabled,
49
+ revision: parsed.data.revision
50
+ };
51
+ }
52
+ //#endregion
53
+ //#region src/service.ts
54
+ var DelegationError = class extends Error {
55
+ code;
56
+ constructor(code, message) {
57
+ super(message);
58
+ this.name = "DelegationError";
59
+ this.code = code;
60
+ }
61
+ };
62
+ /**
63
+ * In-process CAS over the two domain tables. Table `get` is synchronous, so a
64
+ * per-key promise chain serializes check-and-write: two concurrent updates can
65
+ * never both pass the revision check, and a caller only hears success after
66
+ * `put` resolves.
67
+ */
68
+ var DelegationService = class {
69
+ deps;
70
+ chains = /* @__PURE__ */ new Map();
71
+ constructor(deps) {
72
+ this.deps = deps;
73
+ }
74
+ enqueue(key, work) {
75
+ const result = (this.chains.get(key) ?? Promise.resolve()).then(work, work);
76
+ this.chains.set(key, result.then(() => {}, () => {}));
77
+ return result;
78
+ }
79
+ getSettings() {
80
+ return parseSettings(this.deps.settings.get(SETTINGS_KEY));
81
+ }
82
+ updateSettings(defaultEnabled, expectedRevision) {
83
+ return this.enqueue("settings", async () => {
84
+ const current = this.getSettings();
85
+ if (current.revision !== expectedRevision) throw new DelegationError("stale", "dsh-delegation: settings changed; refresh and retry");
86
+ const next = {
87
+ revision: current.revision + 1,
88
+ defaultEnabled
89
+ };
90
+ await this.deps.settings.put(SETTINGS_KEY, next);
91
+ return next;
92
+ });
93
+ }
94
+ /** The parsed session row; undefined means no record (off, revision 0). */
95
+ record(sessionId) {
96
+ return parseSession(this.deps.records.get(sessionId));
97
+ }
98
+ locked(session, agent) {
99
+ return !session || !agent?.runMaintenance || this.deps.hasStarted?.(session) !== false;
100
+ }
101
+ /**
102
+ * The session header: live sessions read the store snapshot; a cold session
103
+ * is resolved through the query engine and the observation is always
104
+ * disposed before returning. Unknown sessions throw `no-session`.
105
+ */
106
+ async requireHeader(sessionId, signal) {
107
+ const live = this.deps.sessionStore?.get(sessionId);
108
+ if (live) return live.header;
109
+ const query = this.deps.sessionQuery;
110
+ if (!query) throw new DelegationError("no-session", `dsh-delegation: no live session ${sessionId}`);
111
+ let observation;
112
+ try {
113
+ observation = await query.observeSession(sessionId, {
114
+ signal,
115
+ projectionMode: "none"
116
+ });
117
+ } catch {
118
+ throw new DelegationError("no-session", `dsh-delegation: no session ${sessionId}`);
119
+ }
120
+ try {
121
+ return observation.header;
122
+ } finally {
123
+ observation[Symbol.dispose]();
124
+ }
125
+ }
126
+ async sessionStatus(sessionId, signal) {
127
+ const session = this.deps.sessionStore?.get(sessionId);
128
+ const header = session ? session.header : await this.requireHeader(sessionId, signal);
129
+ const agent = session ? this.deps.agents?.get(sessionId) : void 0;
130
+ const capable = agent === void 0 ? null : DELEGATION_TOOLS.some((name) => this.deps.tools?.get(name, agent) !== void 0);
131
+ const record = this.record(sessionId);
132
+ return {
133
+ sessionId,
134
+ role: isSubagentSession({ header }) ? "executor" : "coordinator",
135
+ enabled: record?.enabled ?? false,
136
+ revision: record?.revision ?? 0,
137
+ locked: this.locked(session, agent),
138
+ capable
139
+ };
140
+ }
141
+ async updateSession(sessionId, enabled, expectedRevision, signal) {
142
+ const session = this.deps.sessionStore?.get(sessionId);
143
+ const header = session ? session.header : await this.requireHeader(sessionId, signal);
144
+ if (isSubagentSession({ header })) throw new DelegationError("not-top-level", "dsh-delegation: only a top-level session carries the switch");
145
+ await this.enqueue(`session:${sessionId}`, async () => {
146
+ const live = this.deps.sessionStore?.get(sessionId);
147
+ const agent = this.deps.agents?.get(sessionId);
148
+ const requireEditable = () => {
149
+ if (this.locked(live, agent)) throw new DelegationError("session-locked", "dsh-delegation: choose delegation before the session starts");
150
+ };
151
+ requireEditable();
152
+ let entered = false;
153
+ try {
154
+ await agent.runMaintenance(async (maintenanceSignal) => {
155
+ entered = true;
156
+ requireEditable();
157
+ maintenanceSignal.throwIfAborted();
158
+ signal?.throwIfAborted();
159
+ const revision = this.record(sessionId)?.revision ?? 0;
160
+ if (revision !== expectedRevision) throw new DelegationError("stale", "dsh-delegation: session state changed; refresh and retry");
161
+ await this.deps.records.put(sessionId, {
162
+ enabled,
163
+ revision: revision + 1
164
+ });
165
+ });
166
+ } catch (error) {
167
+ if (!entered) throw new DelegationError("session-busy", "dsh-delegation: session is busy; refresh and retry");
168
+ throw error;
169
+ }
170
+ });
171
+ return this.sessionStatus(sessionId, signal);
172
+ }
173
+ /**
174
+ * `agent/created` seeding. Only a fresh ('startup') non-subagent session gets
175
+ * an initial row: a human fork inherits its parent's flag, every other new
176
+ * top-level session takes the current `defaultEnabled`. Resumed, cleared and
177
+ * compacted sessions keep whatever they already have — and stay off when
178
+ * they predate the plugin.
179
+ */
180
+ async seedSession(agent, source) {
181
+ if (source !== "startup") return;
182
+ const session = agent.session;
183
+ if (!session || isSubagentSession(session)) return;
184
+ const id = session.id;
185
+ await this.enqueue(`session:${id}`, async () => {
186
+ if (this.record(id)) return;
187
+ const parentId = typeof session.header?.parentSession === "string" ? session.header.parentSession : void 0;
188
+ const enabled = (parentId ? this.record(parentId) : void 0)?.enabled ?? this.getSettings().defaultEnabled;
189
+ await this.deps.records.put(id, {
190
+ enabled,
191
+ revision: 1
192
+ });
193
+ });
194
+ }
195
+ };
196
+ //#endregion
197
+ //#region src/prompts.ts
198
+ /**
199
+ * System prompt text for delegation mode. Kept literal (the section registers
200
+ * with `interpolate: false`), so no `{{variable}}` syntax may appear here.
201
+ */
202
+ /** Coordinator policy for a top-level session with delegation on. */
203
+ function coordinatorPrompt(tools) {
204
+ return `## Delegation mode
205
+
206
+ Delegation mode is on. You are the coordinator; ${tools.map((name) => `\`${name}\``).join(" / ")} are how you get substantive work done. You own the requirements, division of work, integration decisions, acceptance, and the final response.
207
+
208
+ For a task with multiple components or substantive implementation steps, dispatch a scoped subagent task BEFORE implementing it yourself. A todo list or a promise to delegate is not a delegation. Do not first design every function, read the entire project, or start writing the deliverable. If the split is unclear, delegate a focused discovery task and use its report to choose the next assignments.
209
+
210
+ - Make a short plan that is sufficient to assign work, then call the delegation tool. Prefer a fresh subagent for a self-contained brief. A fork inherits completed turns, not the current in-flight user request: always include the current task and constraints explicitly.
211
+ - Each brief must contain the goal, working directory, allowed files, shared interface/data contracts, acceptance criteria, and what to report. Give each file one active owner. Start independent assignments together; resolve shared contracts before dependent work starts.
212
+ - Subagents read, implement, run commands, test, and fix their assigned work. You may do a brief targeted read or an acceptance check to make a coordination decision; do not use that exception to take over an implementation task.
213
+ - Track the returned subagent ids. Use native completion notifications and send_message for questions, corrections, or follow-up work. Do not repeatedly poll or sleep. Do not claim completion while required work is still running.
214
+ - Inspect the delivered files and verification evidence. Send concrete failures back to the responsible subagent; collect and check the correction. Finish with the usable result, the checks actually performed, and any remaining limitation.
215
+
216
+ A simple question, short rewrite, or genuinely small self-contained task may be completed directly. This exception does not cover building an application or completing a multi-part feature. Keep user-facing updates in the user's language.`;
217
+ }
218
+ /** Executor policy for a subagent whose top-level session has delegation on. */
219
+ const EXECUTOR_PROMPT = `## Delegated task
220
+
221
+ You are a subagent carrying out a task delegated by a coordinating agent. Coordinator instructions that appear earlier in this conversation, for example ones inherited through a fork, do not apply to you.
222
+
223
+ - Do the work yourself: read, search, edit, run commands, and verify as the task requires. Make concrete progress in the assigned files; do not stop at a design or a plan. Do not pass the task on to further subagents unless the brief asks for it or clearly independent parts justify running them in parallel.
224
+ - Stay within the brief. If it is ambiguous, make a reasonable choice and state it; if you are blocked, stop and report what is missing.
225
+ - Respect file ownership and agreed interfaces. Ask the coordinator before changing another worker's files or a shared contract.
226
+ - Verify your result before reporting.
227
+ - End with a concise report: the result, the files or locations changed, the evidence (commands run and their outcome), and unresolved issues. Do not paste full logs.`;
228
+ /** Stable operational reminder; the host persists it only when context changes. */
229
+ function coordinatorReminder(tools) {
230
+ return `Delegation mode: coordinator. For multi-part work, your next implementation action must be a scoped assignment through ${tools.map((name) => `\`${name}\``).join(" / ")}, not doing that implementation yourself. Plan only far enough to dispatch; give workers file ownership and interface contracts, then collect and verify their results. Simple self-contained tasks may be answered directly. This mode remains fixed for this session.`;
231
+ }
232
+ const EXECUTOR_REMINDER = "Delegation mode: executor. Carry out the assigned work in your allowed files and verify it. Earlier coordinator reminders inherited from a parent do not assign you the coordinator role. Report concrete results and evidence to your parent.";
233
+ //#endregion
234
+ //#region src/policy.ts
235
+ /** Ancestor walk bound: subagent chains deeper than this bail out as off. */
236
+ const MAX_PARENT_HOPS = 16;
237
+ /** First non-subagent ancestor reachable through `header.parentSession`. */
238
+ function topLevelSession(session, sessions) {
239
+ const seen = /* @__PURE__ */ new Set([session.id]);
240
+ let current = session;
241
+ for (let hop = 0; hop < MAX_PARENT_HOPS && isSubagentSession(current); hop++) {
242
+ const parentId = typeof current.header?.parentSession === "string" ? current.header.parentSession : void 0;
243
+ if (!parentId || seen.has(parentId)) return void 0;
244
+ seen.add(parentId);
245
+ const parent = sessions(parentId);
246
+ if (!parent) return void 0;
247
+ current = parent;
248
+ }
249
+ return isSubagentSession(current) ? void 0 : current;
250
+ }
251
+ /** Both prompt surfaces must use the same role and capability decision. */
252
+ function delegationPolicy(context, lookups) {
253
+ const session = context.agent?.session;
254
+ if (!session) return void 0;
255
+ if (isSubagentSession(session)) {
256
+ const root = topLevelSession(session, lookups.session);
257
+ return root && lookups.record(root.id)?.enabled ? { role: "executor" } : void 0;
258
+ }
259
+ if (!lookups.record(session.id)?.enabled) return void 0;
260
+ const visible = DELEGATION_TOOLS.filter((name) => lookups.toolVisible(name, context.scope));
261
+ return visible.length ? {
262
+ role: "coordinator",
263
+ tools: visible
264
+ } : void 0;
265
+ }
266
+ /** Static system guidance. No per-step counters or progress belong in this text. */
267
+ function delegationSectionText(context, lookups) {
268
+ const policy = delegationPolicy(context, lookups);
269
+ if (!policy) return "";
270
+ return policy.role === "executor" ? EXECUTOR_PROMPT : coordinatorPrompt(policy.tools);
271
+ }
272
+ /** Stable user-role context snapshot, refreshed by the host after compaction. */
273
+ function delegationReminderText(context, lookups) {
274
+ const policy = delegationPolicy(context, lookups);
275
+ if (!policy) return "";
276
+ return policy.role === "executor" ? EXECUTOR_REMINDER : coordinatorReminder(policy.tools);
277
+ }
278
+ //#endregion
279
+ //#region src/index.ts
280
+ const name = PLUGIN_NAME;
281
+ const inject = [
282
+ "systemPrompt",
283
+ "storageDomain",
284
+ "sessions",
285
+ "agents",
286
+ "tools",
287
+ "sessionQuery",
288
+ "sessionProjections",
289
+ "connection",
290
+ "webServer"
291
+ ];
292
+ function fail(error) {
293
+ if (error instanceof DelegationError) return {
294
+ ok: false,
295
+ error: {
296
+ code: error.code,
297
+ message: error.message
298
+ }
299
+ };
300
+ return {
301
+ ok: false,
302
+ error: {
303
+ code: "internal",
304
+ message: error instanceof Error ? error.message : String(error)
305
+ }
306
+ };
307
+ }
308
+ async function handleRpc(service, endpoint, payload, signal) {
309
+ try {
310
+ switch (endpoint) {
311
+ case "settings": return {
312
+ ok: true,
313
+ value: service.getSettings()
314
+ };
315
+ case "settings.update": {
316
+ const parsed = settingsUpdateSchema.safeParse(payload);
317
+ if (!parsed.success) return {
318
+ ok: false,
319
+ error: {
320
+ code: "bad-request",
321
+ message: "settings update is invalid"
322
+ }
323
+ };
324
+ return {
325
+ ok: true,
326
+ value: await service.updateSettings(parsed.data.defaultEnabled, parsed.data.expectedRevision)
327
+ };
328
+ }
329
+ case "session.status": {
330
+ const parsed = sessionStatusSchema.safeParse(payload);
331
+ if (!parsed.success) return {
332
+ ok: false,
333
+ error: {
334
+ code: "bad-request",
335
+ message: "sessionId is required"
336
+ }
337
+ };
338
+ return {
339
+ ok: true,
340
+ value: await service.sessionStatus(parsed.data.sessionId, signal)
341
+ };
342
+ }
343
+ case "session.update": {
344
+ const parsed = sessionUpdateSchema.safeParse(payload);
345
+ if (!parsed.success) return {
346
+ ok: false,
347
+ error: {
348
+ code: "bad-request",
349
+ message: "session update is invalid"
350
+ }
351
+ };
352
+ return {
353
+ ok: true,
354
+ value: await service.updateSession(parsed.data.sessionId, parsed.data.enabled, parsed.data.expectedRevision, signal)
355
+ };
356
+ }
357
+ default: return {
358
+ ok: false,
359
+ error: {
360
+ code: "not-found",
361
+ message: `unknown endpoint: ${endpoint}`
362
+ }
363
+ };
364
+ }
365
+ } catch (error) {
366
+ return fail(error);
367
+ }
368
+ }
369
+ async function apply(ctx) {
370
+ const host = ctx;
371
+ const domain = await ctx.storageDomain.open(delegationDomain);
372
+ const service = new DelegationService({
373
+ settings: domain.table("settings"),
374
+ records: domain.table("sessions"),
375
+ sessionStore: ctx.sessions,
376
+ agents: ctx.agents,
377
+ tools: ctx.tools,
378
+ sessionQuery: ctx.sessionQuery,
379
+ hasStarted: (session) => {
380
+ const boundary = ctx.sessionProjections.stateOf(session, "turnBoundary");
381
+ return boundary === void 0 || boundary.openTurnStartSeq !== null || boundary.lastTurn > 0;
382
+ }
383
+ });
384
+ ctx.provide("delegation", service);
385
+ ctx.effect(() => () => domain.close(), "delegation.lifecycle");
386
+ ctx.effect(() => ctx.on("agent/created", async ({ agent, source }) => {
387
+ try {
388
+ await service.seedSession(agent, source);
389
+ } catch (error) {
390
+ ctx.logger.warn("dsh-delegation: could not seed session state: %s", error instanceof Error ? error.message : String(error));
391
+ }
392
+ }), "delegation.seed");
393
+ const sectionSessions = ctx.sessions;
394
+ const sectionTools = ctx.tools;
395
+ const lookups = {
396
+ record: (sessionId) => service.record(sessionId),
397
+ session: (id) => sectionSessions?.get(id),
398
+ toolVisible: (tool, scope) => sectionTools?.get(tool, scope) !== void 0
399
+ };
400
+ ctx.effect(() => ctx.systemPrompt.section({
401
+ name: "delegation:policy",
402
+ order: ctx.systemPrompt.getSectionOrder("TOOL_SUBAGENT") + 2,
403
+ interpolate: false,
404
+ text: (context) => delegationSectionText(context, lookups)
405
+ }), "delegation.section");
406
+ ctx.effect(() => ctx.systemPrompt.context({
407
+ name: "delegation:role",
408
+ order: ctx.systemPrompt.getContextOrder("SUBAGENT_DELEGATION") + 2,
409
+ required: true,
410
+ interpolate: false,
411
+ text: (context) => delegationReminderText(context, lookups)
412
+ }), "delegation.context");
413
+ ctx.effect(() => registerHostRpc(host, RPC_CHANNEL, (endpoint, payload, signal) => handleRpc(service, endpoint, payload, signal)), "delegation.rpc");
414
+ }
415
+ //#endregion
416
+ export { DelegationError, DelegationService, EXECUTOR_PROMPT, apply, coordinatorPrompt, delegationSectionText, handleRpc, inject, name };
417
+
418
+ //# sourceMappingURL=index.js.map