@x-otto/prompt 0.1.0-alpha.9 → 0.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,842 @@
1
- import{readFile as e,readdir as t}from"node:fs/promises";import{dirname as n,join as r,relative as i,resolve as a,sep as o}from"node:path";import{fileURLToPath as s}from"node:url";var c=class{baseDir;extension;constructor(e){this.baseDir=e.baseDir,this.extension=e.extension??`.md`}async load(t){let n=r(this.baseDir,`${t}${this.extension}`);try{return{key:t,content:(await e(n,`utf-8`)).trim()}}catch{return null}}async list(){return this.walk(this.baseDir)}async walk(e){let n=[];try{let a=await t(e,{withFileTypes:!0});for(let t of a){let a=r(e,t.name);if(t.isDirectory()){let e=await this.walk(a);n.push(...e)}else if(t.name.endsWith(this.extension)){let e=i(this.baseDir,a).slice(0,-this.extension.length).split(o).join(`/`);n.push(e)}}}catch{}return n}},l=class{baseUrl;getAuth;getHeaders;fetch;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,``),this.getAuth=e.getAuth,this.getHeaders=e.getHeaders,this.fetch=e.fetch??globalThis.fetch,this.timeoutMs=e.timeoutMs??1e4}async load(e){try{let t=await this.request(`/prompts/${encodeURIComponent(e)}`);return t.ok?await t.json():null}catch{return null}}async list(){let e=await this.request(`/prompts`);if(!e.ok)throw Error(`Remote prompt list failed: ${e.status}`);return await e.json()}async request(e,t){let n={"Content-Type":`application/json`};if(this.getAuth){let{token:e}=await this.getAuth();n.Authorization=`Bearer ${e}`}this.getHeaders&&Object.assign(n,await this.getHeaders());let r=new AbortController,i=setTimeout(()=>r.abort(),this.timeoutMs);try{return await this.fetch(`${this.baseUrl}${e}`,{...t,headers:{...n,...t?.headers},signal:r.signal})}finally{clearTimeout(i)}}};function u(e){switch(e.type){case`local`:return new c({baseDir:e.baseDir,extension:e.extension});case`remote`:return new l({baseUrl:e.baseUrl,getAuth:e.getAuth,getHeaders:e.getHeaders,fetch:e.fetch,timeoutMs:e.timeoutMs});default:throw Error(`Unknown prompt provider type: ${e.type}`)}}const d=[`You are a sub-agent: do not interact with the user directly; do not expand the task scope; on completion, report your conclusion and any remaining risks.`].join(`
2
- `),f=[`You are a sub-agent "{agent_name}" in the Otto system.`,`You are responsible for executing one clearly scoped sub-task. Do not interact with users directly, handle overall planning, or further delegate to other sub-agents.`,``,`## Current Task`,`- Title: {task_title}`,`- Description: {task_description}`,`- File scope: {task_files}`,``,`## Execution Requirements`,`- Stay focused on the current task; do not expand scope.`,`- Read relevant code before making changes.`,`- After completion, provide a concise conclusion and note any remaining risks or blockers.`].join(`
3
- `);function p(e){return{"{task_title}":e.taskTitle??`not provided`,"{task_description}":e.taskDescription??`not provided`,"{task_files}":e.taskFiles?.join(`, `)??`not provided`}}function m(e,t={}){let n=e.systemPromptTemplate,r=p(t);for(let[e,t]of Object.entries(r))n=n.replaceAll(e,t);return h(n,e.name),n}function h(e,t){let n=new Set;for(let t of e.matchAll(/\{([a-z][a-z0-9_]*)\}/gi))n.add(t[0]);n.size>0&&console.warn(`[prompt] sub-agent profile "${t}" template has unresolved placeholder(s): ${[...n].join(`, `)} — expected {task_title}/{task_description}/{task_files}. The literal placeholder will reach the model; fix the template or extend the replacement map.`)}function g(e,t={}){let n={...p(t),"{agent_name}":e},r=f;for(let[e,t]of Object.entries(n))r=r.replaceAll(e,t);return r}function _(e,t){let n=e.find(e=>e.name===t);if(n)return n;let r=t.toLowerCase();return e.find(e=>r.endsWith(e.name.toLowerCase())||e.capabilities.some(e=>r.includes(e.toLowerCase()))||e.taskTypes.some(e=>r.includes(e.toLowerCase())))}const v=`[a-zA-Z0-9][a-zA-Z0-9-]*`,y=RegExp(`<!--\\s*requires-capability:\\s*(${v})\\s*-->([\\s\\S]*?)<!--\\s*/requires-capability\\s*-->`,`g`),b=RegExp(`<!--\\s*requires-capability:\\s*(${v})\\s*-->`,`g`);function x(e,t,n){let r=e.replace(y,(e,r,i)=>(n?.knownCapabilities&&!n.knownCapabilities.has(r)&&n.onUnknownCapability?.(r),t?t.has(r)?i:``:i));if(n?.onUnclosedTag)for(let e of r.matchAll(b))n.onUnclosedTag(e[1]??``);return r}var S=class{provider;knownCapabilities;leadGuidance=null;constructor(e){this.provider=e.provider,this.knownCapabilities=e.knownCapabilities}async load(e){return(await this.provider.load(e))?.content??null}async assemble(e){this.leadGuidance===null&&(this.leadGuidance=await this.load(`lead-guidance`)??``);let t=x(this.leadGuidance,e,{knownCapabilities:this.knownCapabilities,onUnknownCapability:e=>console.warn(`[prompt] lead-guidance.md references unknown capability "${e}" (typo or renamed key in CAPABILITY_TOOL_MAP?) — the gated section is silently dropped`),onUnclosedTag:e=>console.warn(`[prompt] lead-guidance.md has an unclosed requires-capability tag: "${e}"`)});return{stable:t,volatile:``,render:()=>t}}async assemblePreset(e={preset:`main`},t){return e.preset===`subagent`?e.profile?e.profile.promptMode===`append`?(await this.assemble(t)).render():m(e.profile,e.context):g(e.agentName,e.context):(await this.assemble(t)).render()}assembleSubAgentTail(e){if(e.preset===`subagent`&&e.profile&&e.profile.promptMode===`append`)return m(e.profile,e.context)}async loadRuntimeLessonsTemplate(){return this.load(`lesson/runtime-lessons`)}};const C=a(n(s(import.meta.url)),`..`,`prompts`);function w(e,t){if(e.length===0)return``;let n=e.map((e,t)=>`${t+1}. [${e.tags.join(`, `)}] ${e.trigger} → ${e.insight}`);return(t??`### Runtime Lessons
4
- The following lessons were learned from previous sessions:
5
- {lessons}`).replace(`{lessons}`,n.join(`
6
- `))}export{C as BUILTIN_PROMPTS_DIR,l as HttpPromptProvider,c as LocalPromptProvider,S as PromptManager,d as SUBAGENT_GUARDRAILS,g as assembleGenericSubAgentPrompt,m as assembleSubAgentPrompt,w as buildLessonInjection,u as createPromptProvider,x as gateByToolAvailability,_ as resolveAgentProfile};
7
- //# sourceMappingURL=index.js.map
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { PROMPT_CONTEXT_ORIGIN, SLOTS, TIMINGS, isMemoryRecallSectionName, systemTextOf, truncateUtf8Bytes } from "@x-otto/kernel";
4
+ import { defineComponent, onCleanup } from "@x-otto/universal";
5
+ import { createHash } from "node:crypto";
6
+ import { list, stringEnum } from "@x-otto/settings";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ //#region src/local-provider.ts
10
+ var LocalPromptProvider = class {
11
+ baseDir;
12
+ extension;
13
+ constructor(options) {
14
+ this.baseDir = options.baseDir;
15
+ this.extension = options.extension ?? ".md";
16
+ }
17
+ async load(key) {
18
+ const filePath = join(this.baseDir, `${key}${this.extension}`);
19
+ try {
20
+ return {
21
+ status: "loaded",
22
+ entry: {
23
+ key,
24
+ content: (await readFile(filePath, "utf8")).trim()
25
+ }
26
+ };
27
+ } catch (error) {
28
+ if (error.code === "ENOENT") return {
29
+ status: "not-loaded",
30
+ key
31
+ };
32
+ return {
33
+ status: "failed",
34
+ failure: {
35
+ key,
36
+ message: error instanceof Error ? error.message : String(error)
37
+ }
38
+ };
39
+ }
40
+ }
41
+ };
42
+
43
+ //#endregion
44
+ //#region src/prompt-manager.ts
45
+ const BASE_KEY = "lead-guidance";
46
+ const SUBAGENT_NOTE_KEY = "subagent-note";
47
+ var PromptManager = class {
48
+ provider;
49
+ cache = /* @__PURE__ */ new Map();
50
+ constructor(options) {
51
+ this.provider = options.provider;
52
+ }
53
+ async load(key) {
54
+ return this.provider.load(key);
55
+ }
56
+ async loadCached(key) {
57
+ const cached = this.cache.get(key);
58
+ if (cached !== void 0) return cached;
59
+ const result = await this.load(key);
60
+ if (result.status !== "failed") this.cache.set(key, result);
61
+ return result;
62
+ }
63
+ async assemble(depth) {
64
+ const failures = [];
65
+ const parts = [];
66
+ const base = await this.loadCached(BASE_KEY);
67
+ if (base.status === "loaded") parts.push(base.entry.content);
68
+ else if (base.status === "failed") failures.push(base.failure);
69
+ if (depth !== void 0 && depth !== 0) {
70
+ const note = await this.loadCached(SUBAGENT_NOTE_KEY);
71
+ if (note.status === "loaded") parts.push(note.entry.content);
72
+ else if (note.status === "failed") failures.push(note.failure);
73
+ }
74
+ return {
75
+ text: parts.filter((part) => part.trim() !== "").join("\n\n"),
76
+ failures
77
+ };
78
+ }
79
+ };
80
+
81
+ //#endregion
82
+ //#region src/context-fragment.ts
83
+ function contextFragmentBytes(content) {
84
+ return new TextEncoder().encode(content).length;
85
+ }
86
+ function boundFragment(content, budgetBytes) {
87
+ const truncated = truncateUtf8Bytes(content, budgetBytes);
88
+ if (truncated === content) return content;
89
+ return truncated.trimEnd() + "\n[context truncated: budget exceeded]";
90
+ }
91
+
92
+ //#endregion
93
+ //#region src/prefix-epoch.ts
94
+ function contentLengthOf(message) {
95
+ if (typeof message.content === "string") return message.content.length;
96
+ return JSON.stringify(message.content).length;
97
+ }
98
+ function messageIdentityOf(message) {
99
+ if (message.uuid !== void 0) return message.uuid;
100
+ const timestamp = "timestamp" in message ? String(message.timestamp) : "";
101
+ return `${message.role}\u0000${timestamp}\u0000${String(contentLengthOf(message))}`;
102
+ }
103
+ function prefixEpochOf(turn, messages) {
104
+ const head = messages[0];
105
+ return {
106
+ turn,
107
+ surfaceLength: messages.length,
108
+ surfaceHead: head === void 0 ? "" : messageIdentityOf(head)
109
+ };
110
+ }
111
+ function isPrefixEpochStale(frozen, current) {
112
+ if (frozen.turn !== current.turn) return true;
113
+ if (current.surfaceHead !== frozen.surfaceHead) return true;
114
+ return current.surfaceLength < frozen.surfaceLength;
115
+ }
116
+
117
+ //#endregion
118
+ //#region src/prefix-freezer.ts
119
+ const FROZEN_SESSION_LIMIT = 256;
120
+ function createPrefixFreezer(limit = 256) {
121
+ const frozen = /* @__PURE__ */ new Map();
122
+ const divergedSessions = /* @__PURE__ */ new Set();
123
+ return {
124
+ divergedSessions,
125
+ frozenOf: (prefixKey) => frozen.get(prefixKey),
126
+ remember: (prefixKey, value) => {
127
+ frozen.set(prefixKey, value);
128
+ divergedSessions.delete(prefixKey);
129
+ while (frozen.size > limit) {
130
+ const oldest = frozen.keys().next();
131
+ if (oldest.done === true) return;
132
+ frozen.delete(oldest.value);
133
+ divergedSessions.delete(oldest.value);
134
+ }
135
+ }
136
+ };
137
+ }
138
+
139
+ //#endregion
140
+ //#region src/state.ts
141
+ function createPromptSectionState() {
142
+ return {
143
+ warnedSectionsByRequest: /* @__PURE__ */ new Map(),
144
+ prefixFreezer: createPrefixFreezer()
145
+ };
146
+ }
147
+ function openWarnedSections(state, requestId) {
148
+ const warned = /* @__PURE__ */ new Set();
149
+ state.warnedSectionsByRequest.set(requestId, warned);
150
+ return warned;
151
+ }
152
+ function closeWarnedSections(state, requestId) {
153
+ state.warnedSectionsByRequest.delete(requestId);
154
+ }
155
+ function warnedSectionsOf(state, requestId) {
156
+ return state.warnedSectionsByRequest.get(requestId);
157
+ }
158
+
159
+ //#endregion
160
+ //#region src/section-catalog.ts
161
+ const BASE_INJECT_PRIORITY = 5;
162
+ var DuplicateSectionPriorityError = class extends Error {
163
+ constructor(priority, owner, incoming) {
164
+ super(`prompt section priority ${priority} is already used by "${owner}" — pick a distinct priority for "${incoming}"`);
165
+ this.name = "DuplicateSectionPriorityError";
166
+ }
167
+ };
168
+ var ReservedSectionPriorityError = class extends Error {
169
+ constructor(priority, name) {
170
+ super(`prompt section "${name}" priority ${priority} must be greater than ${5}: a section running at or before base-inject would make output.systemPrompt non-empty before base-inject runs, silently skipping lead-guidance.md`);
171
+ this.name = "ReservedSectionPriorityError";
172
+ }
173
+ };
174
+ function sectionFamilyOf(name) {
175
+ const separator = name.indexOf(":");
176
+ return separator === -1 ? name : name.slice(0, separator);
177
+ }
178
+ function bySectionOrder(left, right) {
179
+ if (left.priority !== right.priority) return left.priority - right.priority;
180
+ return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
181
+ }
182
+ function orderSections(contributions, disabled) {
183
+ const byPriority = /* @__PURE__ */ new Map();
184
+ const ordered = [];
185
+ for (const [key, section] of contributions) {
186
+ if (section.placement !== "system") continue;
187
+ if (section.priority <= 5) throw new ReservedSectionPriorityError(section.priority, section.name);
188
+ const family = sectionFamilyOf(section.name);
189
+ const owner = byPriority.get(section.priority);
190
+ if (owner !== void 0 && owner.key !== key && owner.family !== family) throw new DuplicateSectionPriorityError(section.priority, owner.key, section.name);
191
+ byPriority.set(section.priority, {
192
+ key,
193
+ family,
194
+ name: section.name
195
+ });
196
+ ordered.push(section);
197
+ }
198
+ return ordered.sort(bySectionOrder).filter((section) => disabled?.has(section.name) !== true);
199
+ }
200
+ function applyBudget(diagnostics, section, content, allowedBytes) {
201
+ const sizeBytes = contextFragmentBytes(content);
202
+ if (sizeBytes > allowedBytes) diagnostics.push({
203
+ code: "PROMPT_SECTION_TRUNCATED",
204
+ severity: "warning",
205
+ section: section.name,
206
+ message: `section="${section.name}" budget=${allowedBytes}B declared=${section.budgetBytes}B size=${sizeBytes}B`
207
+ });
208
+ return boundFragment(content, allowedBytes);
209
+ }
210
+ const SECTION_REMOVED_DIGEST = "removed";
211
+ function sectionDigestOf(text) {
212
+ return createHash("sha256").update(text).digest("hex").slice(0, 16);
213
+ }
214
+ function surfaceChains(messages) {
215
+ const chains = /* @__PURE__ */ new Map();
216
+ for (const message of messages) {
217
+ if (message.role !== "user" || message.contextSection === void 0) continue;
218
+ const { name, digest } = message.contextSection;
219
+ if (isMemoryRecallSectionName(name)) continue;
220
+ chains.set(name, [...chains.get(name) ?? [], digest]);
221
+ }
222
+ return chains;
223
+ }
224
+ function isSameChain(visible, accepted) {
225
+ return visible.length === accepted.length && visible.every((digest, index) => accepted[index]?.digest === digest);
226
+ }
227
+ function seededChains(surface) {
228
+ const chains = /* @__PURE__ */ new Map();
229
+ for (const [name, digests] of surfaceChains(surface)) {
230
+ const accepted = digests.map((digest) => ({
231
+ digest,
232
+ text: void 0
233
+ }));
234
+ chains.set(name, accepted);
235
+ }
236
+ return chains;
237
+ }
238
+ function revisionMessage(name, digest, content) {
239
+ return {
240
+ role: "user",
241
+ internal: true,
242
+ origin: PROMPT_CONTEXT_ORIGIN,
243
+ timestamp: 0,
244
+ content,
245
+ contextSection: {
246
+ name,
247
+ digest
248
+ }
249
+ };
250
+ }
251
+ function revertedContent(name) {
252
+ return `[section update: ${name}]\nThis section is back to the frozen version in the system prompt; ignore earlier updates to it.`;
253
+ }
254
+ function removedContent(name) {
255
+ return `[section removed: ${name}]\nThis section no longer applies; ignore its earlier content.`;
256
+ }
257
+ function revisionMessages(frozen, computed, surface, failed) {
258
+ const visible = surfaceChains(surface);
259
+ const messages = [];
260
+ const accepted = /* @__PURE__ */ new Map();
261
+ const present = /* @__PURE__ */ new Set();
262
+ const baseOf = (name) => {
263
+ const chain = frozen.chains.get(name) ?? [];
264
+ const seen = visible.get(name) ?? [];
265
+ const frozenText = frozen.parts.get(name);
266
+ if (seen.length === 0) return frozenText === void 0 ? { isKnown: true } : {
267
+ isKnown: true,
268
+ digest: sectionDigestOf(frozenText),
269
+ text: frozenText
270
+ };
271
+ if (!isSameChain(seen, chain)) return { isKnown: false };
272
+ const last = chain[chain.length - 1];
273
+ return {
274
+ isKnown: true,
275
+ digest: last?.digest,
276
+ text: last?.text
277
+ };
278
+ };
279
+ for (const part of computed) {
280
+ present.add(part.name);
281
+ const digest = sectionDigestOf(part.text);
282
+ const base = baseOf(part.name);
283
+ if (base.isKnown && base.digest === digest) continue;
284
+ const frozenText = frozen.parts.get(part.name);
285
+ const content = !base.isKnown ? fullRevisionContent(part.name, part.text) : frozenText === part.text ? revertedContent(part.name) : revisionContentOf(part.name, base.text, part.text);
286
+ messages.push(revisionMessage(part.name, digest, content));
287
+ accepted.set(part.name, {
288
+ digest,
289
+ text: part.text
290
+ });
291
+ }
292
+ const names = new Set([...frozen.parts.keys(), ...visible.keys()]);
293
+ for (const name of names) {
294
+ if (present.has(name) || failed.has(name)) continue;
295
+ const base = baseOf(name);
296
+ if (base.isKnown && (base.digest === "removed" || base.digest === void 0)) continue;
297
+ messages.push(revisionMessage(name, SECTION_REMOVED_DIGEST, removedContent(name)));
298
+ accepted.set(name, {
299
+ digest: SECTION_REMOVED_DIGEST,
300
+ text: void 0
301
+ });
302
+ }
303
+ return {
304
+ messages,
305
+ accepted
306
+ };
307
+ }
308
+ function acceptRevisions(frozen, surface, plan) {
309
+ const visible = surfaceChains(surface);
310
+ for (const [name, revision] of plan.accepted) {
311
+ const seen = visible.get(name) ?? [];
312
+ const chain = frozen.chains.get(name) ?? [];
313
+ const base = isSameChain(seen, chain) ? chain : seen.map((digest) => ({
314
+ digest,
315
+ text: void 0
316
+ }));
317
+ frozen.chains.set(name, [...base, revision]);
318
+ }
319
+ }
320
+ async function composeSections(state, sections, input, base) {
321
+ const diagnostics = [];
322
+ const parts = [];
323
+ const blocks = base.filter((block) => block.text !== "").map((block) => ({
324
+ text: block.text,
325
+ stable: true
326
+ }));
327
+ const requestId = input.snapshot?.requestId;
328
+ const requestTotalBytes = input.snapshot?.budget.sections?.totalBytes ?? Number.POSITIVE_INFINITY;
329
+ let remainingBytes = requestTotalBytes;
330
+ for (const section of sections) {
331
+ const allowedBytes = Math.min(section.budgetBytes, remainingBytes);
332
+ if (allowedBytes <= 0) {
333
+ diagnostics.push({
334
+ code: "PROMPT_SECTION_TRUNCATED",
335
+ severity: "warning",
336
+ section: section.name,
337
+ message: `section="${section.name}" rendered empty: request section budget ${requestTotalBytes}B exhausted (declared=${section.budgetBytes}B)`
338
+ });
339
+ continue;
340
+ }
341
+ let computed;
342
+ try {
343
+ const value = await section.compute({
344
+ ...input,
345
+ allowedBytes
346
+ });
347
+ if (value !== void 0 && typeof value !== "string") {
348
+ diagnostics.push({
349
+ code: "PROMPT_SECTION_FAILED",
350
+ severity: "error",
351
+ section: section.name,
352
+ message: `section="${section.name}" returned surface-only section messages and was skipped`
353
+ });
354
+ continue;
355
+ }
356
+ computed = value;
357
+ } catch (error) {
358
+ diagnostics.push({
359
+ code: "PROMPT_SECTION_FAILED",
360
+ severity: "error",
361
+ section: section.name,
362
+ message: `section="${section.name}" failed to compute and was skipped: ${error instanceof Error ? error.message : String(error)}`
363
+ });
364
+ continue;
365
+ }
366
+ const block = computed ? applyBudget(diagnostics, section, computed, allowedBytes) : "";
367
+ if (block) {
368
+ parts.push({
369
+ name: section.name,
370
+ text: block
371
+ });
372
+ remainingBytes -= contextFragmentBytes(block);
373
+ const stable = (section.cacheHint ?? "stable") === "stable";
374
+ const last = blocks[blocks.length - 1];
375
+ if (last && last.stable === stable) last.text = `${last.text}\n\n${block}`;
376
+ else blocks.push({
377
+ text: `\n\n${block}`,
378
+ stable
379
+ });
380
+ }
381
+ }
382
+ let breakpoint = -1;
383
+ for (let i = 0; i < blocks.length; i += 1) {
384
+ if (blocks[i]?.stable !== true) break;
385
+ breakpoint = i;
386
+ }
387
+ const currentDiagnosticSections = new Set(diagnostics.map((diagnostic) => diagnostic.section).filter((section) => section !== void 0));
388
+ const warnedSections = requestId === void 0 ? void 0 : warnedSectionsOf(state, requestId);
389
+ if (warnedSections !== void 0) {
390
+ for (const name of warnedSections) if (!currentDiagnosticSections.has(name)) warnedSections.delete(name);
391
+ }
392
+ return {
393
+ parts,
394
+ system: blocks.map((block, index) => index === breakpoint ? {
395
+ text: block.text,
396
+ cache: "ephemeral"
397
+ } : { text: block.text }),
398
+ diagnostics
399
+ };
400
+ }
401
+ function createContextCatalog(contributions) {
402
+ return { list() {
403
+ return orderSections(contributions()).map((section) => ({
404
+ name: section.name,
405
+ priority: section.priority,
406
+ budgetBytes: section.budgetBytes,
407
+ placement: section.placement,
408
+ ...section.cacheHint !== void 0 ? { cacheHint: section.cacheHint } : {}
409
+ }));
410
+ } };
411
+ }
412
+ function registerSectionComposer(deps, state, contributions, priority, options = {}) {
413
+ deps.contribute(TIMINGS.systemPromptTransform, "prompt::sections", {
414
+ name: "prompt::sections",
415
+ timing: TIMINGS.systemPromptTransform,
416
+ kind: "interceptor",
417
+ priority,
418
+ handle: async (input, output) => {
419
+ const typedInput = input;
420
+ const typedOutput = output;
421
+ if (typedOutput.failure) return;
422
+ const requestId = typedInput.snapshot?.requestId;
423
+ const warnedSections = requestId === void 0 ? /* @__PURE__ */ new Set() : openWarnedSections(state, requestId);
424
+ try {
425
+ let ordered;
426
+ try {
427
+ ordered = orderSections(contributions(), options.disabled?.());
428
+ } catch (error) {
429
+ const message = error instanceof Error ? error.message : String(error);
430
+ typedOutput.failure = {
431
+ code: error instanceof ReservedSectionPriorityError ? "PROMPT_SECTION_PRIORITY_RESERVED" : error instanceof DuplicateSectionPriorityError ? "PROMPT_SECTION_PRIORITY_DUPLICATE" : "PROMPT_SECTION_INVALID",
432
+ message
433
+ };
434
+ return;
435
+ }
436
+ const result = await composeSections(state, ordered, typedInput, typedOutput.systemPrompt);
437
+ const sessionId = typedInput.sessionId ?? typedInput.snapshot?.sessionId ?? "";
438
+ const disabledKey = [...options.disabled?.() ?? []].sort().join(",");
439
+ const prefixKey = `${sessionId}\u0000${typedInput.cwd ?? typedInput.snapshot?.cwd ?? ""}\u0000${disabledKey}`;
440
+ const computedText = systemTextOf(result.system);
441
+ const failedSections = new Set(result.diagnostics.filter((diagnostic) => diagnostic.code === "PROMPT_SECTION_FAILED").map((diagnostic) => diagnostic.section).filter((name) => name !== void 0));
442
+ const surface = typedInput.snapshot?.messages ?? [];
443
+ const epoch = prefixEpochOf(typedInput.snapshot?.turn ?? 0, surface);
444
+ const cached = state.prefixFreezer.frozenOf(prefixKey);
445
+ const frozen = cached !== void 0 && !isPrefixEpochStale(cached.epoch, epoch) ? cached : void 0;
446
+ if (frozen === void 0) {
447
+ const fresh = {
448
+ text: computedText,
449
+ parts: new Map(result.parts.map((part) => [part.name, part.text])),
450
+ chains: seededChains(surface),
451
+ epoch
452
+ };
453
+ if (computedText !== "") state.prefixFreezer.remember(prefixKey, fresh);
454
+ typedOutput.systemPrompt = result.system;
455
+ const reconciled = revisionMessages(fresh, result.parts, surface, failedSections);
456
+ if (reconciled.messages.length > 0) {
457
+ acceptRevisions(fresh, surface, reconciled);
458
+ typedOutput.surfaceAppend = [...typedOutput.surfaceAppend ?? [], ...reconciled.messages];
459
+ }
460
+ } else {
461
+ typedOutput.systemPrompt = frozen.text === "" ? [] : [{
462
+ text: frozen.text,
463
+ cache: "ephemeral"
464
+ }];
465
+ const revisions = revisionMessages(frozen, result.parts, surface, failedSections);
466
+ if (revisions.messages.length > 0) {
467
+ acceptRevisions(frozen, surface, revisions);
468
+ typedOutput.surfaceAppend = [...typedOutput.surfaceAppend ?? [], ...revisions.messages];
469
+ }
470
+ if (computedText !== frozen.text && !state.prefixFreezer.divergedSessions.has(prefixKey)) {
471
+ state.prefixFreezer.divergedSessions.add(prefixKey);
472
+ deps.diagnose({
473
+ source: "prompt-context",
474
+ severity: "info",
475
+ sessionId,
476
+ timing: TIMINGS.systemPromptTransform,
477
+ code: "PROMPT_PREFIX_FROZEN_DIVERGENCE",
478
+ message: `frozen system prefix kept; recomputed prefix differs by ${String(Math.abs(computedText.length - frozen.text.length))} char(s)`
479
+ });
480
+ }
481
+ }
482
+ typedOutput.diagnostics = [...typedOutput.diagnostics ?? [], ...result.diagnostics];
483
+ for (const diagnostic of result.diagnostics) {
484
+ if (diagnostic.section === void 0) continue;
485
+ if (warnedSections.has(diagnostic.section)) continue;
486
+ warnedSections.add(diagnostic.section);
487
+ deps.diagnose({
488
+ source: "prompt-context",
489
+ severity: diagnostic.severity,
490
+ sessionId: typedInput.snapshot.sessionId,
491
+ timing: TIMINGS.systemPromptTransform,
492
+ code: diagnostic.code,
493
+ message: diagnostic.message
494
+ });
495
+ }
496
+ } finally {
497
+ if (requestId !== void 0) closeWarnedSections(state, requestId);
498
+ }
499
+ }
500
+ });
501
+ }
502
+ const REVISION_DELTA_MIN_SECTION_BYTES = 4096;
503
+ const REVISION_DELTA_MAX_SHARE = .5;
504
+ function lineBlockChange(previous, next) {
505
+ const previousLines = previous.split("\n");
506
+ const nextLines = next.split("\n");
507
+ const shortest = Math.min(previousLines.length, nextLines.length);
508
+ let head = 0;
509
+ while (head < shortest && previousLines[head] === nextLines[head]) head += 1;
510
+ let tail = 0;
511
+ while (tail < shortest - head && previousLines[previousLines.length - 1 - tail] === nextLines[nextLines.length - 1 - tail]) tail += 1;
512
+ const isPureInsertion = head + tail === previousLines.length;
513
+ const anchorBefore = isPureInsertion && head > 0 ? 1 : 0;
514
+ const anchorAfter = isPureInsertion && head === 0 && tail > 0 ? 1 : 0;
515
+ return {
516
+ removed: previousLines.slice(head - anchorBefore, previousLines.length - tail + anchorAfter).join("\n"),
517
+ added: nextLines.slice(head - anchorBefore, nextLines.length - tail + anchorAfter).join("\n")
518
+ };
519
+ }
520
+ function fullRevisionContent(name, text) {
521
+ return `[section update: ${name}]\nThe content below replaces the previous content of this section.\n\n${text}`;
522
+ }
523
+ function deltaRevisionContent(name, previous, next) {
524
+ const change = lineBlockChange(previous, next);
525
+ return `[section update: ${name}]\nThis section changed since its latest version above. Only the block below differs — every line before and after it is unchanged. Replace the old block with the new block and use the result as the current section.
526
+
527
+ --- old block ---\n${change.removed === "" ? "(empty)" : change.removed}\n--- new block ---\n${change.added === "" ? "(empty)" : change.added}`;
528
+ }
529
+ function revisionContentOf(name, previous, next) {
530
+ const previousText = previous ?? "";
531
+ const full = fullRevisionContent(name, next);
532
+ if (contextFragmentBytes(next) < 4096) return full;
533
+ const delta = deltaRevisionContent(name, previousText, next);
534
+ if (contextFragmentBytes(delta) > contextFragmentBytes(full) * .5) return full;
535
+ return delta;
536
+ }
537
+
538
+ //#endregion
539
+ //#region src/section-policy.ts
540
+ const SECTIONS_DISABLED_FIELD_SPEC = Object.freeze({
541
+ key: "prompt.sections.disabled",
542
+ env: "OTTO_PROMPT_SECTIONS_DISABLED",
543
+ default: [],
544
+ parse: (raw) => list(raw),
545
+ ownership: "trusted-project"
546
+ });
547
+ const SECTIONS_PRESET_FIELD_SPEC = Object.freeze({
548
+ key: "prompt.sections.preset",
549
+ env: "OTTO_PROMPT_SECTIONS_PRESET",
550
+ default: "full",
551
+ parse: (raw) => stringEnum(["full", "lean"])(raw),
552
+ ownership: "trusted-project"
553
+ });
554
+ const LEAN_DISABLED_SECTIONS = ["subagent::delegation-guidance"];
555
+ function resolveDisabledSections(disabled, preset) {
556
+ const names = new Set(disabled ?? []);
557
+ if (preset === "lean") for (const name of LEAN_DISABLED_SECTIONS) names.add(name);
558
+ return names;
559
+ }
560
+
561
+ //#endregion
562
+ //#region src/contexts/environment.ts
563
+ const ENVIRONMENT_TITLE = "Runtime environment (updates only when changed):";
564
+ function formatLocalDate(timestamp) {
565
+ const date = new Date(timestamp);
566
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
567
+ }
568
+ function renderEnvironment(runtimeEnv, clock, input) {
569
+ const lines = [ENVIRONMENT_TITLE, `cwd: ${input.cwd}`];
570
+ if (runtimeEnv) {
571
+ lines.push(`platform: ${runtimeEnv.platform()}`);
572
+ const shell = runtimeEnv.shell();
573
+ if (shell !== void 0) lines.push(`shell: ${shell}`);
574
+ }
575
+ lines.push(`current_date: ${formatLocalDate(clock.now())}`);
576
+ if (runtimeEnv) {
577
+ lines.push(`timezone: ${runtimeEnv.timezone()}`);
578
+ const branch = runtimeEnv.gitBranch(input.cwd);
579
+ if (branch !== void 0) lines.push(`git_branch: ${branch}`);
580
+ }
581
+ return lines.join("\n");
582
+ }
583
+ function createEnvironmentContext(runtimeEnv, clock) {
584
+ return {
585
+ name: "prompt::environment",
586
+ priority: 10,
587
+ budgetBytes: 1024,
588
+ placement: "surface",
589
+ compute(input) {
590
+ return renderEnvironment(runtimeEnv, clock, input);
591
+ }
592
+ };
593
+ }
594
+
595
+ //#endregion
596
+ //#region src/space-prompt-materializer.ts
597
+ function createSpacePromptMaterializer(options) {
598
+ return {
599
+ kind: options.kind,
600
+ component(capability) {
601
+ const Materialized = (ctx) => {
602
+ const parsed = options.read(capability.declared);
603
+ if (!parsed.ok) {
604
+ options.warn?.(`space ${options.kind} "${capability.entry.id}" rejected: ${parsed.reason}`);
605
+ return;
606
+ }
607
+ const declaration = parsed.declaration;
608
+ const title = capability.entry.title;
609
+ const contribution = {
610
+ name: `${options.namePrefix}:${capability.entry.id}`,
611
+ priority: options.priority,
612
+ budgetBytes: options.budgetBytes,
613
+ placement: "system",
614
+ cacheHint: "stable",
615
+ compute: (input) => options.sessionApplies !== void 0 && !options.sessionApplies(input.sessionId, capability.entry.id) ? void 0 : options.render(title, declaration)
616
+ };
617
+ ctx.effect(() => {
618
+ ctx.contribute(SLOTS.contexts, contribution.name, contribution);
619
+ });
620
+ };
621
+ return Materialized;
622
+ }
623
+ };
624
+ }
625
+ function nonEmptyStringsOf(value) {
626
+ if (!Array.isArray(value)) return;
627
+ const kept = value.filter((entry) => typeof entry === "string" && entry !== "");
628
+ return kept.length === 0 ? void 0 : kept;
629
+ }
630
+ function optionalString(record, key) {
631
+ const value = record[key];
632
+ return typeof value === "string" && value !== "" ? value : void 0;
633
+ }
634
+
635
+ //#endregion
636
+ //#region src/space-agent-materializer.ts
637
+ const SPACE_AGENT_KIND = "agent";
638
+ const AGENT_PERSONA_PRIORITY = 620;
639
+ const AGENT_PERSONA_BUDGET_BYTES = 8 * 1024;
640
+ function readPersonaDeclaration(declared) {
641
+ const instructions = declared["instructions"];
642
+ if (typeof instructions !== "string" || instructions.trim() === "") return {
643
+ ok: false,
644
+ reason: "agent capability requires non-empty \"instructions\""
645
+ };
646
+ const tools = nonEmptyStringsOf(declared["tools"]);
647
+ const preset = optionalString(declared, "preset");
648
+ const model = optionalString(declared, "model");
649
+ const effort = optionalString(declared, "effort");
650
+ return {
651
+ ok: true,
652
+ declaration: {
653
+ instructions,
654
+ ...preset === void 0 ? {} : { preset },
655
+ ...tools === void 0 ? {} : { tools },
656
+ ...model === void 0 ? {} : { model },
657
+ ...effort === void 0 ? {} : { effort }
658
+ }
659
+ };
660
+ }
661
+ function renderPersonaSection(title, declaration) {
662
+ const lines = [`## Space role: ${title}`];
663
+ lines.push("", declaration.instructions.trim());
664
+ if (declaration.tools !== void 0) lines.push("", "Recommended tools for this role (activate deferred ones with tool_search):", ...declaration.tools.map((name) => `- ${name}`));
665
+ return lines.join("\n");
666
+ }
667
+ function createSpaceAgentMaterializer(deps = {}) {
668
+ const personaOfSession = deps.personaOfSession;
669
+ return createSpacePromptMaterializer({
670
+ kind: SPACE_AGENT_KIND,
671
+ namePrefix: "space-role",
672
+ priority: AGENT_PERSONA_PRIORITY,
673
+ budgetBytes: AGENT_PERSONA_BUDGET_BYTES,
674
+ read: readPersonaDeclaration,
675
+ render: renderPersonaSection,
676
+ ...deps.warn === void 0 ? {} : { warn: deps.warn },
677
+ ...personaOfSession === void 0 ? {} : { sessionApplies: (sessionId, capabilityId) => {
678
+ const personaId = personaOfSession(sessionId);
679
+ return personaId === void 0 || personaId === capabilityId;
680
+ } }
681
+ });
682
+ }
683
+
684
+ //#endregion
685
+ //#region src/persona-contribution.ts
686
+ const PERSONA_CONTRIBUTION_KEY = "personas";
687
+ function recordOf(value) {
688
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
689
+ }
690
+ function declarativePersonaCapabilitiesOf(item) {
691
+ const declared = item.manifest.contributes?.[PERSONA_CONTRIBUTION_KEY];
692
+ if (!Array.isArray(declared)) return [];
693
+ const scope = item.scope;
694
+ return declared.flatMap((element) => {
695
+ const record = recordOf(element);
696
+ const id = record?.["id"];
697
+ if (record === void 0 || typeof id !== "string" || id === "") return [];
698
+ const { id: _id, title: _title, ...declaration } = record;
699
+ return [{
700
+ entry: {
701
+ kind: SPACE_AGENT_KIND,
702
+ id,
703
+ title: typeof record["title"] === "string" ? record["title"] : id,
704
+ scope,
705
+ enabled: true,
706
+ pluginId: item.manifest.id
707
+ },
708
+ declared: declaration,
709
+ directory: item.directory
710
+ }];
711
+ });
712
+ }
713
+ function createPersonaContribution(deps) {
714
+ const materializer = createSpaceAgentMaterializer(deps);
715
+ const Contribution = (ctx, config) => {
716
+ const capabilities = declarativePersonaCapabilitiesOf(config.item);
717
+ for (const capability of capabilities) ctx.mount(materializer.component(capability), void 0, { key: `declarative-persona:${capability.entry.id}` });
718
+ const stopObserving = config.observe(() => capabilities.length > 0 ? "active" : "not-applicable", async () => void 0);
719
+ onCleanup(() => stopObserving());
720
+ };
721
+ return {
722
+ capability: SPACE_AGENT_KIND,
723
+ component: Contribution
724
+ };
725
+ }
726
+
727
+ //#endregion
728
+ //#region src/component.ts
729
+ const SECTION_COMPOSER_PRIORITY = 5 + 1;
730
+ const Prompt = defineComponent("PromptComponent", (ctx, options) => {
731
+ const hooks = ctx.consume(SLOTS.hooks);
732
+ const contributions = ctx.consumeAll(SLOTS.contexts);
733
+ const personaSessions = ctx.maybe(SLOTS.sessions);
734
+ const state = ctx.resource("section-state", () => createPromptSectionState(), () => {}, { hmr: "preserve" });
735
+ const manager = ctx.resource("prompt-manager", () => new PromptManager({ provider: new LocalPromptProvider({ baseDir: options.promptsDir }) }), () => {});
736
+ ctx.effect(() => {
737
+ const registry = hooks();
738
+ const settingsManager = ctx.maybe(SLOTS.settings)?.();
739
+ let disabledField;
740
+ let presetField;
741
+ try {
742
+ disabledField = settingsManager?.registerField(SECTIONS_DISABLED_FIELD_SPEC, "prompt");
743
+ presetField = settingsManager?.registerField(SECTIONS_PRESET_FIELD_SPEC, "prompt");
744
+ } catch (error) {
745
+ disabledField?.dispose();
746
+ throw error;
747
+ }
748
+ const disabledSections = () => resolveDisabledSections(disabledField?.get(), presetField?.get());
749
+ const contribute = (timing, key, spec) => ctx.contributor(`hook:${timing}`)(key, spec);
750
+ contribute(TIMINGS.systemPromptTransform, "prompt::base-inject", {
751
+ name: "prompt::base-inject",
752
+ timing: TIMINGS.systemPromptTransform,
753
+ kind: "interceptor",
754
+ priority: 5,
755
+ handle: async (input, output) => {
756
+ const typedInput = input;
757
+ const typed = output;
758
+ if (systemTextOf(typed.systemPrompt).trim()) return;
759
+ const assembled = await manager.assemble(typedInput.depth);
760
+ const failure = assembled.failures[0];
761
+ if (failure !== void 0) {
762
+ typed.failure = {
763
+ code: "PROMPT_LOAD_FAILED",
764
+ message: `prompt template "${failure.key}" could not be loaded: ${failure.message}`
765
+ };
766
+ return;
767
+ }
768
+ if (!assembled.text.trim()) {
769
+ typed.failure = {
770
+ code: "BASE_EMPTY",
771
+ message: "base system prompt (lead-guidance) loaded empty; the model would run without any system prompt"
772
+ };
773
+ return;
774
+ }
775
+ typed.systemPrompt = [{ text: assembled.text }];
776
+ }
777
+ });
778
+ registerSectionComposer({
779
+ contribute,
780
+ diagnose: (input) => {
781
+ registry?.emitAndWait(TIMINGS.runtimeDiagnostic, input).catch(() => void 0);
782
+ }
783
+ }, state, contributions, SECTION_COMPOSER_PRIORITY, { disabled: disabledSections });
784
+ return () => {
785
+ disabledField?.dispose();
786
+ presetField?.dispose();
787
+ };
788
+ });
789
+ const catalog = ctx.resource("section-catalog", () => createContextCatalog(contributions), () => {});
790
+ const environment = createEnvironmentContext(options.runtimeEnv, options.clock ?? { now: () => Date.now() });
791
+ ctx.contribute(SLOTS.contexts, environment.name, environment);
792
+ const reportSpaceWarning = (code, message) => {
793
+ hooks()?.emitAndWait(TIMINGS.runtimeDiagnostic, {
794
+ source: "prompt-context",
795
+ severity: "warning",
796
+ code,
797
+ message
798
+ }).catch(() => void 0);
799
+ };
800
+ const agentMaterializerDeps = {
801
+ warn: (message) => reportSpaceWarning("SPACE_AGENT_PERSONA_REJECTED", message),
802
+ ...personaSessions === void 0 ? {} : { personaOfSession: (sessionId) => personaSessions()?.metaOf(sessionId)?.config?.persona?.personaId }
803
+ };
804
+ ctx.contribute(SLOTS.extensionContributions, SPACE_AGENT_KIND, createPersonaContribution(agentMaterializerDeps));
805
+ ctx.provide(SLOTS.contextCatalog, () => catalog);
806
+ });
807
+
808
+ //#endregion
809
+ //#region src/prompt-budget.ts
810
+ const PROMPT_LEAD_HARD_MAX_BYTES = 7168;
811
+ const PROMPT_LEAD_REGRESSION_MAX_BYTES = 6862;
812
+ const PROMPT_GUIDANCE_REGRESSION_MAX_BYTES = 2871;
813
+
814
+ //#endregion
815
+ //#region src/builtin-prompts-dir.ts
816
+ function resolveBuiltinPromptsDir() {
817
+ return resolve(dirname(fileURLToPath(import.meta.url)), "..", "prompts");
818
+ }
819
+ const BUILTIN_PROMPTS_DIR = resolveBuiltinPromptsDir();
820
+
821
+ //#endregion
822
+ //#region src/dangling-terms.ts
823
+ const DANGLING_TERMS = [
824
+ "todo-list tool",
825
+ "todo list",
826
+ "update todos",
827
+ "task-inspection",
828
+ "task-control",
829
+ "file-state refresh",
830
+ "engine_budget",
831
+ "engine_continuation",
832
+ "session tokens used",
833
+ "Model Slot",
834
+ "critique slot",
835
+ "named agent",
836
+ "task_delegate",
837
+ "task_inspect",
838
+ "capture_file_state"
839
+ ];
840
+
841
+ //#endregion
842
+ export { BASE_INJECT_PRIORITY, BUILTIN_PROMPTS_DIR, DANGLING_TERMS, DuplicateSectionPriorityError, LEAN_DISABLED_SECTIONS, LocalPromptProvider, PROMPT_GUIDANCE_REGRESSION_MAX_BYTES, PROMPT_LEAD_HARD_MAX_BYTES, PROMPT_LEAD_REGRESSION_MAX_BYTES, Prompt, PromptManager, ReservedSectionPriorityError, SECTIONS_DISABLED_FIELD_SPEC, SECTIONS_PRESET_FIELD_SPEC, boundFragment, composeSections, contextFragmentBytes, createContextCatalog, createEnvironmentContext, createPromptSectionState, orderSections, registerSectionComposer, resolveDisabledSections };