@agimon-ai/doompi-plan 0.0.1-alpha.2 → 0.0.1-alpha.21
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/README.md +44 -19
- package/dist/adapters/pi/extension.cjs +2 -0
- package/dist/adapters/pi/extension.cjs.map +1 -0
- package/dist/{extension.d.cts → adapters/pi/extension.d.cts} +1 -1
- package/dist/adapters/pi/extension.d.cts.map +1 -0
- package/dist/{extension.d.mts → adapters/pi/extension.d.mts} +1 -1
- package/dist/adapters/pi/extension.d.mts.map +1 -0
- package/dist/adapters/pi/extension.mjs +2 -0
- package/dist/adapters/pi/extension.mjs.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.cjs +2 -0
- package/dist/adapters/telemetry/logSinkTelemetry.cjs.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.cts +34 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.cts.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.mts +34 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.mts.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.mjs +2 -0
- package/dist/adapters/telemetry/logSinkTelemetry.mjs.map +1 -0
- package/dist/config.cjs +1 -2
- package/dist/config.d.cts +2 -14
- package/dist/config.d.mts +2 -14
- package/dist/config.mjs +1 -2
- package/dist/extensions/doom.cjs +1 -1
- package/dist/extensions/doom.cjs.map +1 -1
- package/dist/extensions/doom.mjs +1 -1
- package/dist/extensions/doom.mjs.map +1 -1
- package/dist/extensions/pi.cjs +1 -1
- package/dist/extensions/pi.cjs.map +1 -1
- package/dist/extensions/pi.d.cts +1 -1
- package/dist/extensions/pi.d.mts +1 -1
- package/dist/extensions/pi.mjs +1 -1
- package/dist/extensions/pi.mjs.map +1 -1
- package/dist/fableFlow.cjs +1 -3
- package/dist/fableFlow.d.cts +2 -66
- package/dist/fableFlow.d.mts +2 -66
- package/dist/fableFlow.mjs +1 -3
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +1 -1
- package/dist/logSinkTelemetry.cjs +1 -2
- package/dist/logSinkTelemetry.d.cts +2 -24
- package/dist/logSinkTelemetry.d.mts +2 -24
- package/dist/logSinkTelemetry.mjs +1 -2
- package/dist/planConfig.cjs +1 -2
- package/dist/planConfig.d.cts +2 -0
- package/dist/planConfig.d.mts +2 -0
- package/dist/planConfig.mjs +1 -2
- package/dist/planMode.cjs +1 -6
- package/dist/planMode.d.cts +3 -75
- package/dist/planMode.d.mts +3 -75
- package/dist/planMode.mjs +1 -6
- package/dist/prompts.cjs +1 -3
- package/dist/prompts.d.cts +2 -24
- package/dist/prompts.d.mts +2 -24
- package/dist/prompts.mjs +1 -3
- package/dist/schemas/plan/config.cjs +2 -0
- package/dist/schemas/plan/config.cjs.map +1 -0
- package/dist/schemas/plan/config.d.cts +14 -0
- package/dist/schemas/plan/config.d.cts.map +1 -0
- package/dist/schemas/plan/config.d.mts +14 -0
- package/dist/schemas/plan/config.d.mts.map +1 -0
- package/dist/schemas/plan/config.mjs +2 -0
- package/dist/schemas/plan/config.mjs.map +1 -0
- package/dist/schemas/plan/planConfig.cjs +2 -0
- package/dist/schemas/plan/planConfig.cjs.map +1 -0
- package/dist/schemas/plan/planConfig.d.cts +21 -0
- package/dist/schemas/plan/planConfig.d.cts.map +1 -0
- package/dist/schemas/plan/planConfig.d.mts +21 -0
- package/dist/schemas/plan/planConfig.d.mts.map +1 -0
- package/dist/schemas/plan/planConfig.mjs +2 -0
- package/dist/schemas/plan/planConfig.mjs.map +1 -0
- package/dist/services/plan/fableFlow.cjs +3 -0
- package/dist/services/plan/fableFlow.cjs.map +1 -0
- package/dist/services/plan/fableFlow.d.cts +66 -0
- package/dist/services/plan/fableFlow.d.cts.map +1 -0
- package/dist/services/plan/fableFlow.d.mts +66 -0
- package/dist/services/plan/fableFlow.d.mts.map +1 -0
- package/dist/services/plan/fableFlow.mjs +3 -0
- package/dist/services/plan/fableFlow.mjs.map +1 -0
- package/dist/services/plan/planMode.cjs +6 -0
- package/dist/services/plan/planMode.cjs.map +1 -0
- package/dist/services/plan/planMode.d.cts +79 -0
- package/dist/services/plan/planMode.d.cts.map +1 -0
- package/dist/services/plan/planMode.d.mts +79 -0
- package/dist/services/plan/planMode.d.mts.map +1 -0
- package/dist/services/plan/planMode.mjs +6 -0
- package/dist/services/plan/planMode.mjs.map +1 -0
- package/dist/services/plan/prompts.cjs +3 -0
- package/dist/services/plan/prompts.cjs.map +1 -0
- package/dist/services/plan/prompts.d.cts +24 -0
- package/dist/services/plan/prompts.d.cts.map +1 -0
- package/dist/services/plan/prompts.d.mts +24 -0
- package/dist/services/plan/prompts.d.mts.map +1 -0
- package/dist/services/plan/prompts.mjs +3 -0
- package/dist/services/plan/prompts.mjs.map +1 -0
- package/package.json +16 -8
- package/dist/config.cjs.map +0 -1
- package/dist/config.d.cts.map +0 -1
- package/dist/config.d.mts.map +0 -1
- package/dist/config.mjs.map +0 -1
- package/dist/extension.cjs +0 -2
- package/dist/extension.cjs.map +0 -1
- package/dist/extension.d.cts.map +0 -1
- package/dist/extension.d.mts.map +0 -1
- package/dist/extension.mjs +0 -2
- package/dist/extension.mjs.map +0 -1
- package/dist/fableFlow.cjs.map +0 -1
- package/dist/fableFlow.d.cts.map +0 -1
- package/dist/fableFlow.d.mts.map +0 -1
- package/dist/fableFlow.mjs.map +0 -1
- package/dist/logSinkTelemetry.cjs.map +0 -1
- package/dist/logSinkTelemetry.d.cts.map +0 -1
- package/dist/logSinkTelemetry.d.mts.map +0 -1
- package/dist/logSinkTelemetry.mjs.map +0 -1
- package/dist/planConfig.cjs.map +0 -1
- package/dist/planConfig.mjs.map +0 -1
- package/dist/planMode.cjs.map +0 -1
- package/dist/planMode.d.cts.map +0 -1
- package/dist/planMode.d.mts.map +0 -1
- package/dist/planMode.mjs.map +0 -1
- package/dist/prompts.cjs.map +0 -1
- package/dist/prompts.d.cts.map +0 -1
- package/dist/prompts.d.mts.map +0 -1
- package/dist/prompts.mjs.map +0 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { PlanningModeConfig } from "./config.cjs";
|
|
2
|
+
import { ConfigSection } from "@agimon-ai/doompi-ui/config";
|
|
3
|
+
|
|
4
|
+
//#region src/schemas/plan/planConfig.d.ts
|
|
5
|
+
declare const PLAN_CONFIG_SECTION_ID = "planning";
|
|
6
|
+
interface PlanSettingDescriptor {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly label: string;
|
|
9
|
+
readonly keyPath: readonly string[];
|
|
10
|
+
readonly placeholder: string;
|
|
11
|
+
readonly detail: string;
|
|
12
|
+
/** Present for a closed set; the panel offers these rather than free text. */
|
|
13
|
+
readonly options?: readonly string[];
|
|
14
|
+
readonly read: (config: PlanningModeConfig | undefined) => string | undefined;
|
|
15
|
+
}
|
|
16
|
+
declare const PLAN_SETTINGS: readonly PlanSettingDescriptor[];
|
|
17
|
+
declare function planSettingByFieldId(fieldId: string): PlanSettingDescriptor | undefined;
|
|
18
|
+
declare function planConfigSections(config: PlanningModeConfig | undefined, notice?: string): readonly ConfigSection[];
|
|
19
|
+
//#endregion
|
|
20
|
+
export { PLAN_CONFIG_SECTION_ID, PLAN_SETTINGS, planConfigSections, planSettingByFieldId };
|
|
21
|
+
//# sourceMappingURL=planConfig.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planConfig.d.cts","names":[],"sources":["../../../src/schemas/plan/planConfig.ts"],"mappings":";;;;cAiBa,sBAAA;AAAA,UASH,qBAAA;EAAA,SACC,EAAA;EAAA,SACA,KAAA;EAAA,SACA,OAAA;EAAA,SACA,WAAA;EAAA,SACA,MAAA;EAGe;EAAA,SADf,OAAA;EAAA,SACA,IAAA,GAAO,MAAA,EAAQ,kBAAA;AAAA;AAAA,cAGb,aAAA,WAAwB,qBAAA;AAAA,iBA6CrB,oBAAA,CAAqB,OAAA,WAAkB,qBAAA;AAAA,iBAUvC,kBAAA,CAAmB,MAAA,EAAQ,kBAAA,cAAgC,MAAA,qBAA2B,aAAA"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { PlanningModeConfig } from "./config.mjs";
|
|
2
|
+
import { ConfigSection } from "@agimon-ai/doompi-ui/config";
|
|
3
|
+
|
|
4
|
+
//#region src/schemas/plan/planConfig.d.ts
|
|
5
|
+
declare const PLAN_CONFIG_SECTION_ID = "planning";
|
|
6
|
+
interface PlanSettingDescriptor {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly label: string;
|
|
9
|
+
readonly keyPath: readonly string[];
|
|
10
|
+
readonly placeholder: string;
|
|
11
|
+
readonly detail: string;
|
|
12
|
+
/** Present for a closed set; the panel offers these rather than free text. */
|
|
13
|
+
readonly options?: readonly string[];
|
|
14
|
+
readonly read: (config: PlanningModeConfig | undefined) => string | undefined;
|
|
15
|
+
}
|
|
16
|
+
declare const PLAN_SETTINGS: readonly PlanSettingDescriptor[];
|
|
17
|
+
declare function planSettingByFieldId(fieldId: string): PlanSettingDescriptor | undefined;
|
|
18
|
+
declare function planConfigSections(config: PlanningModeConfig | undefined, notice?: string): readonly ConfigSection[];
|
|
19
|
+
//#endregion
|
|
20
|
+
export { PLAN_CONFIG_SECTION_ID, PLAN_SETTINGS, planConfigSections, planSettingByFieldId };
|
|
21
|
+
//# sourceMappingURL=planConfig.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planConfig.d.mts","names":[],"sources":["../../../src/schemas/plan/planConfig.ts"],"mappings":";;;;cAiBa,sBAAA;AAAA,UASH,qBAAA;EAAA,SACC,EAAA;EAAA,SACA,KAAA;EAAA,SACA,OAAA;EAAA,SACA,WAAA;EAAA,SACA,MAAA;EAGe;EAAA,SADf,OAAA;EAAA,SACA,IAAA,GAAO,MAAA,EAAQ,kBAAA;AAAA;AAAA,cAGb,aAAA,WAAwB,qBAAA;AAAA,iBA6CrB,oBAAA,CAAqB,OAAA,WAAkB,qBAAA;AAAA,iBAUvC,kBAAA,CAAmB,MAAA,EAAQ,kBAAA,cAAgC,MAAA,qBAA2B,aAAA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{DOOM_PLANNING_THINKING_LEVELS as e}from"@agimon-ai/doompi-config";import{CONFIG_ACTION as t}from"@agimon-ai/doompi-ui/config";const n=`planning`,r=[`modes`,n],i=`main`,a=`subagents`,o=`inherit the session model`,s=`inherit`,c=[{id:`main.model`,label:`main model`,keyPath:[...r,i,`model`],placeholder:o,detail:`Model the main agent switches to while plan mode is on.`,read:e=>e?.main?.model},{id:`main.thinking`,label:`main thinking`,keyPath:[...r,i,`thinking`],placeholder:s,detail:`Thinking level appended to the main model while planning.`,options:e,read:e=>e?.main?.thinking},{id:`subagents.model`,label:`subagent model`,keyPath:[...r,a,`model`],placeholder:o,detail:`Model forced onto delegated planning subagents.`,read:e=>e?.subagents?.model},{id:`subagents.thinking`,label:`subagent thinking`,keyPath:[...r,a,`thinking`],placeholder:s,detail:`Thinking level appended to the subagent model.`,options:e,read:e=>e?.subagents?.thinking},{id:`plansdirectory`,label:`plans directory`,keyPath:[...r,`plansDirectory`],placeholder:`~/.pi/plans`,detail:`Absolute, repo-relative, or under ~. Written plans land here.`,read:e=>e?.plansDirectory}];function l(e){return c.find(t=>t.id===e)}function u(e){return e.options?.map(e=>({id:e,label:e,action:t.set}))}function d(e,t){return[{id:n,title:`planning`,order:30,detail:`plan mode`,fields:c.map(t=>{let n=t.read(e),r=u(t);return{id:t.id,label:t.label,kind:r?`enum`:`text`,keyPath:t.keyPath.join(`.`),placeholder:t.placeholder,detail:t.detail,...n?{value:n}:{},...r?{choices:r}:{}}}),...t?{notice:t,noticeLevel:`error`}:{}}]}export{n as PLAN_CONFIG_SECTION_ID,c as PLAN_SETTINGS,d as planConfigSections,l as planSettingByFieldId};
|
|
2
|
+
//# sourceMappingURL=planConfig.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planConfig.mjs","names":[],"sources":["../../../src/schemas/plan/planConfig.ts"],"sourcesContent":["/**\n * Plan mode's slice of the `SPC e c` config panel.\n *\n * Plan mode reads `modes.planning` from disk on every activation, so an edit\n * here lands on the next time the mode is turned on with no restart and nothing\n * to invalidate.\n *\n * The descriptor table is the whole design: the panel renders it and the write\n * handler looks the key path back up in it, so adding a setting means adding a\n * row rather than a case.\n */\n\nimport { DOOM_PLANNING_THINKING_LEVELS } from '@agimon-ai/doompi-config';\nimport type { ConfigChoice, ConfigField, ConfigSection } from '@agimon-ai/doompi-ui/config';\nimport { CONFIG_ACTION } from '@agimon-ai/doompi-ui/config';\nimport type { PlanningModeConfig } from './config.ts';\n\nexport const PLAN_CONFIG_SECTION_ID = 'planning';\nconst SECTION_ORDER = 30;\nconst PLANNING_PATH = ['modes', PLAN_CONFIG_SECTION_ID] as const;\nconst MAIN_KEY = 'main';\nconst SUBAGENTS_KEY = 'subagents';\n/** Both agents fall back to the session's own settings when left unset. */\nconst INHERIT_MODEL = 'inherit the session model';\nconst INHERIT_THINKING = 'inherit';\n\ninterface PlanSettingDescriptor {\n readonly id: string;\n readonly label: string;\n readonly keyPath: readonly string[];\n readonly placeholder: string;\n readonly detail: string;\n /** Present for a closed set; the panel offers these rather than free text. */\n readonly options?: readonly string[];\n readonly read: (config: PlanningModeConfig | undefined) => string | undefined;\n}\n\nexport const PLAN_SETTINGS: readonly PlanSettingDescriptor[] = [\n {\n id: 'main.model',\n label: 'main model',\n keyPath: [...PLANNING_PATH, MAIN_KEY, 'model'],\n placeholder: INHERIT_MODEL,\n detail: 'Model the main agent switches to while plan mode is on.',\n read: (config) => config?.main?.model,\n },\n {\n id: 'main.thinking',\n label: 'main thinking',\n keyPath: [...PLANNING_PATH, MAIN_KEY, 'thinking'],\n placeholder: INHERIT_THINKING,\n detail: 'Thinking level appended to the main model while planning.',\n options: DOOM_PLANNING_THINKING_LEVELS,\n read: (config) => config?.main?.thinking,\n },\n {\n id: 'subagents.model',\n label: 'subagent model',\n keyPath: [...PLANNING_PATH, SUBAGENTS_KEY, 'model'],\n placeholder: INHERIT_MODEL,\n detail: 'Model forced onto delegated planning subagents.',\n read: (config) => config?.subagents?.model,\n },\n {\n id: 'subagents.thinking',\n label: 'subagent thinking',\n keyPath: [...PLANNING_PATH, SUBAGENTS_KEY, 'thinking'],\n placeholder: INHERIT_THINKING,\n detail: 'Thinking level appended to the subagent model.',\n options: DOOM_PLANNING_THINKING_LEVELS,\n read: (config) => config?.subagents?.thinking,\n },\n {\n id: 'plansdirectory',\n label: 'plans directory',\n keyPath: [...PLANNING_PATH, 'plansDirectory'],\n placeholder: '~/.pi/plans',\n detail: 'Absolute, repo-relative, or under ~. Written plans land here.',\n read: (config) => config?.plansDirectory,\n },\n];\n\nexport function planSettingByFieldId(fieldId: string): PlanSettingDescriptor | undefined {\n return PLAN_SETTINGS.find((setting) => setting.id === fieldId);\n}\n\nfunction choicesFor(setting: PlanSettingDescriptor): ConfigChoice[] | undefined {\n // `set` rather than a bespoke action: choosing a level is the same write as\n // typing one, so it shares the handler.\n return setting.options?.map((option) => ({ id: option, label: option, action: CONFIG_ACTION.set }));\n}\n\nexport function planConfigSections(config: PlanningModeConfig | undefined, notice?: string): readonly ConfigSection[] {\n const fields: ConfigField[] = PLAN_SETTINGS.map((setting) => {\n const value = setting.read(config);\n const choices = choicesFor(setting);\n return {\n id: setting.id,\n label: setting.label,\n kind: choices ? ('enum' as const) : ('text' as const),\n keyPath: setting.keyPath.join('.'),\n placeholder: setting.placeholder,\n detail: setting.detail,\n ...(value ? { value } : {}),\n ...(choices ? { choices } : {}),\n };\n });\n return [\n {\n id: PLAN_CONFIG_SECTION_ID,\n title: 'planning',\n order: SECTION_ORDER,\n detail: 'plan mode',\n fields,\n ...(notice ? { notice, noticeLevel: 'error' as const } : {}),\n },\n ];\n}\n"],"mappings":"qIAiBA,MAAa,EAAyB,WAEhC,EAAgB,CAAC,QAAS,EAAuB,CACjD,EAAW,OACX,EAAgB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AI,CAClC,YAAa,EAAQ,YACrB,OAAQ,EAAQ,OAChB,GAAI,EAAQ,CAAE,QAAO,CAAG,EAAE,CAC1B,GAAI,EAAU,CAAE,UAAS,CAAG,EAAE,CAC/B,EAQO,CACN,GAAI,EAAS,CAAE,SAAQ,YAAa,QAAkB,CAAG,EAAE,CAC5D,CACF"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
require(`../../_virtual/_rolldown/runtime.cjs`);let e=require(`node:buffer`),t=require(`node:crypto`);const n=`@agimon-ai/doompi-plan`,r=`claude`,i=`fable`,a=`claude/fable-plan-v1`,o=[/(?:api[_-]?key|access[_-]?token|client[_-]?secret|password|private[_-]?key|authorization|bearer)\s*[:=]/iu,/-----BEGIN [A-Z ]*PRIVATE KEY-----/u,/\bsk-[A-Za-z0-9_-]{16,}\b/u,/\bgh[pousr]_[A-Za-z0-9_]{16,}\b/u];function s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c(e){for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(e<=31||e===127))return!0}return!1}function l(e){return o.some(t=>t.test(e))}function u(t,n,r=!0){if(typeof t!=`string`)throw Error(`${n} must be a string.`);let i=t.trim();if(!i&&r)throw Error(`${n} must not be empty.`);if(e.Buffer.byteLength(i,`utf8`)>4096||c(i))throw Error(`${n} exceeds the bounded Fable text limit or contains control characters.`);if(l(i))throw Error(`${n} appears to contain a credential.`);return i}function d(e,t,n=!0){if(!Array.isArray(e))throw Error(`${t} must be an array.`);if(e.length>24)throw Error(`${t} exceeds the bounded item limit.`);let r=e.map((e,n)=>u(e,`${t}[${n}]`));if(n&&r.length===0)throw Error(`${t} must contain at least one item.`);return r}function f(e,t){if(typeof e!=`string`)throw Error(`${t} must be a string.`);let n=e.trim();if(!n||n.length>512||c(n))throw Error(`${t} is not a safe source path.`);if(l(n))throw Error(`${t} appears to contain a credential.`);return n}function p(e){if(!Array.isArray(e))throw Error(`verifiedFindings must be an array.`);if(e.length>24)throw Error(`verifiedFindings exceeds the bounded item limit.`);return e.map((e,t)=>{if(!s(e))throw Error(`verifiedFindings[${t}] must be an object.`);if(Object.keys(e).some(e=>e!==`path`&&e!==`finding`))throw Error(`verifiedFindings[${t}] contains an unsupported field.`);return{path:f(e.path,`verifiedFindings[${t}].path`),finding:u(e.finding,`verifiedFindings[${t}].finding`)}})}function m(e,t,n){let r=new Set(t),i=Object.keys(e).find(e=>!r.has(e));if(i)throw Error(`${n} contains unsupported field '${i}'.`)}function h(t){if(!s(t))throw Error(`Fable packet must be an object.`);m(t,[`goal`,`constraints`,`decisions`,`verifiedFindings`,`inferredFindings`,`unresolvedQuestions`,`currentPlan`],`Fable packet`);let n={goal:d(t.goal,`goal`),constraints:d(t.constraints,`constraints`,!1),decisions:d(t.decisions,`decisions`,!1),verifiedFindings:p(t.verifiedFindings),inferredFindings:d(t.inferredFindings,`inferredFindings`,!1),unresolvedQuestions:d(t.unresolvedQuestions,`unresolvedQuestions`,!1),...t.currentPlan===void 0?{}:{currentPlan:u(t.currentPlan,`currentPlan`,!1)}};if(e.Buffer.byteLength(JSON.stringify(n),`utf8`)>32768)throw Error(`Fable packet exceeds the bounded packet size.`);return n}function g(e){return l([e.draft,e.review].filter(e=>e!==void 0).join(`
|
|
2
|
+
`))?{operationId:e.operationId,status:`failed`,stage:`failed`,durationMs:e.durationMs,errorCode:`unsafe_output`}:e}function _(e,t){return{operationId:e,status:`timed_out`,stage:`interrupted`,durationMs:Math.max(0,Date.now()-t),errorCode:`timeout`}}function v(e){let o,s=(t=`Fable operation cancelled.`)=>{let n=o;if(n){if(!n.cancelSent){n.cancelSent=!0;try{e.broker?.cancel(n.operationId,t)}catch(t){e.onError?.(t)}}n.controller.abort(Error(t))}};return{run:async(c,l)=>{if(o)throw Error(`A Fable operation is already active for this session.`);if(!e.isAuthorized())throw Error(`The Fable capability profile is not authorized.`);let u=h(c),d=`fable-${(0,t.randomUUID)()}`,f=Date.now(),p=new AbortController;o={operationId:d,controller:p,cancelSent:!1},e.onStage?.(`draft`);let m=()=>p.abort(l?.reason);l&&(l.addEventListener(`abort`,m,{once:!0}),l.aborted&&m());let v={requester:n,operationId:d,runtime:r,model:i,profile:a,packet:u},y,b=!1;try{if(!e.broker)return _(d,f);let t=e.broker.start(v,p.signal),n=new Promise(e=>{p.signal.addEventListener(`abort`,()=>{b||e({operationId:d,status:`cancelled`,stage:`cancelled`,durationMs:Math.max(0,Date.now()-f),errorCode:`cancelled`})},{once:!0})}),r=e.timeoutMs===void 0?void 0:new Promise(t=>{y=setTimeout(()=>{b=!0,s(`Fable operation timed out.`),t(_(d,f))},e.timeoutMs)}),i=g(r===void 0?await Promise.race([t,n]):await Promise.race([t,r,n]));return e.onStage?.(i.status===`completed`?`completed`:i.status===`cancelled`?`cancelled`:i.stage),i}catch(t){e.onError?.(t);let n={operationId:d,status:`failed`,stage:`failed`,durationMs:Math.max(0,Date.now()-f),errorCode:`unavailable`};return e.onStage?.(`failed`),n}finally{y&&clearTimeout(y),l&&l.removeEventListener(`abort`,m),o=void 0}},cancel:s,isActive:()=>o!==void 0}}exports.FABLE_PLAN_MODEL=i,exports.FABLE_PLAN_PROFILE=a,exports.FABLE_PLAN_REQUESTER=n,exports.FABLE_PLAN_RUNTIME=r,exports.FABLE_PROVIDER_SOURCE=`@agimon-ai/doompi-team`,exports.MAX_FABLE_ARRAY_ITEMS=24,exports.MAX_FABLE_PACKET_BYTES=32768,exports.MAX_FABLE_TEXT_BYTES=4096,exports.containsSuspectedCredential=l,exports.createFablePlanFlow=v,exports.sanitizeFablePacket=h;
|
|
3
|
+
//# sourceMappingURL=fableFlow.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fableFlow.cjs","names":["Buffer"],"sources":["../../../src/services/plan/fableFlow.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { randomUUID } from 'node:crypto';\n\nexport const FABLE_PROVIDER_SOURCE = '@agimon-ai/doompi-team';\nexport const FABLE_PLAN_REQUESTER = '@agimon-ai/doompi-plan';\nexport const FABLE_PLAN_RUNTIME = 'claude';\nexport const FABLE_PLAN_MODEL = 'fable';\nexport const FABLE_PLAN_PROFILE = 'claude/fable-plan-v1';\nexport const MAX_FABLE_PACKET_BYTES = 32 * 1024;\nexport const MAX_FABLE_TEXT_BYTES = 4 * 1024;\nexport const MAX_FABLE_ARRAY_ITEMS = 24;\n\nconst SECRET_PATTERNS = [\n /(?:api[_-]?key|access[_-]?token|client[_-]?secret|password|private[_-]?key|authorization|bearer)\\s*[:=]/iu,\n /-----BEGIN [A-Z ]*PRIVATE KEY-----/u,\n /\\bsk-[A-Za-z0-9_-]{16,}\\b/u,\n /\\bgh[pousr]_[A-Za-z0-9_]{16,}\\b/u,\n];\nconst CONTROL_CHARACTER_MAX = 31;\nconst DELETE_CHARACTER = 127;\nconst MAX_SOURCE_PATH_LENGTH = 512;\n\nexport interface FablePlanFinding {\n path: string;\n finding: string;\n}\n\nexport interface FablePlanPacket {\n goal: string[];\n constraints: string[];\n decisions: string[];\n verifiedFindings: FablePlanFinding[];\n inferredFindings: string[];\n unresolvedQuestions: string[];\n currentPlan?: string;\n}\n\nexport type FablePlanStatus = 'completed' | 'failed' | 'timed_out' | 'cancelled' | 'interrupted';\nexport type FablePlanStage = 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';\n\nexport interface FablePlanResult {\n operationId: string;\n status: FablePlanStatus;\n stage: FablePlanStage;\n draft?: string;\n review?: string;\n draftRunId?: string;\n reviewRunId?: string;\n durationMs: number;\n errorCode?: string;\n}\n\nexport interface FablePlanRequest {\n requester: typeof FABLE_PLAN_REQUESTER;\n operationId: string;\n runtime: typeof FABLE_PLAN_RUNTIME;\n model: typeof FABLE_PLAN_MODEL;\n profile: typeof FABLE_PLAN_PROFILE;\n packet: FablePlanPacket;\n}\n\nexport interface FablePlanBroker {\n start(request: FablePlanRequest, signal: AbortSignal): Promise<FablePlanResult>;\n cancel(operationId: string, reason: string): void;\n}\n\nexport interface FableFlowOptions {\n broker?: FablePlanBroker;\n isAuthorized: () => boolean;\n timeoutMs?: number;\n onStage?: (stage: FableStage) => void;\n onError?: (error: unknown) => void;\n}\n\nexport type FableStage = 'idle' | 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';\n\nexport interface FablePlanFlow {\n run(value: unknown, signal?: AbortSignal): Promise<FablePlanResult>;\n cancel(reason?: string): void;\n isActive(): boolean;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (const character of value) {\n const code = character.codePointAt(0);\n if (code !== undefined && (code <= CONTROL_CHARACTER_MAX || code === DELETE_CHARACTER)) return true;\n }\n return false;\n}\n\nexport function containsSuspectedCredential(value: string): boolean {\n return SECRET_PATTERNS.some((pattern) => pattern.test(value));\n}\n\nfunction boundedText(value: unknown, field: string, required = true): string {\n if (typeof value !== 'string') throw new Error(`${field} must be a string.`);\n const text = value.trim();\n if (!text && required) throw new Error(`${field} must not be empty.`);\n if (Buffer.byteLength(text, 'utf8') > MAX_FABLE_TEXT_BYTES || hasControlCharacter(text)) {\n throw new Error(`${field} exceeds the bounded Fable text limit or contains control characters.`);\n }\n if (containsSuspectedCredential(text)) throw new Error(`${field} appears to contain a credential.`);\n return text;\n}\n\nfunction boundedList(value: unknown, field: string, required = true): string[] {\n if (!Array.isArray(value)) throw new Error(`${field} must be an array.`);\n if (value.length > MAX_FABLE_ARRAY_ITEMS) throw new Error(`${field} exceeds the bounded item limit.`);\n const items = value.map((item, index) => boundedText(item, `${field}[${index}]`));\n if (required && items.length === 0) throw new Error(`${field} must contain at least one item.`);\n return items;\n}\n\nfunction boundedPath(value: unknown, field: string): string {\n if (typeof value !== 'string') throw new Error(`${field} must be a string.`);\n const sourcePath = value.trim();\n if (!sourcePath || sourcePath.length > MAX_SOURCE_PATH_LENGTH || hasControlCharacter(sourcePath)) {\n throw new Error(`${field} is not a safe source path.`);\n }\n if (containsSuspectedCredential(sourcePath)) throw new Error(`${field} appears to contain a credential.`);\n return sourcePath;\n}\n\nfunction boundedFindings(value: unknown): FablePlanFinding[] {\n if (!Array.isArray(value)) throw new Error('verifiedFindings must be an array.');\n if (value.length > MAX_FABLE_ARRAY_ITEMS) throw new Error('verifiedFindings exceeds the bounded item limit.');\n return value.map((item, index) => {\n if (!isRecord(item)) throw new Error(`verifiedFindings[${index}] must be an object.`);\n const keys = Object.keys(item);\n if (keys.some((key) => key !== 'path' && key !== 'finding')) {\n throw new Error(`verifiedFindings[${index}] contains an unsupported field.`);\n }\n return {\n path: boundedPath(item.path, `verifiedFindings[${index}].path`),\n finding: boundedText(item.finding, `verifiedFindings[${index}].finding`),\n };\n });\n}\n\nfunction assertAllowedKeys(value: Record<string, unknown>, keys: readonly string[], field: string): void {\n const allowed = new Set(keys);\n const unexpected = Object.keys(value).find((key) => !allowed.has(key));\n if (unexpected) throw new Error(`${field} contains unsupported field '${unexpected}'.`);\n}\n\nexport function sanitizeFablePacket(value: unknown): FablePlanPacket {\n if (!isRecord(value)) throw new Error('Fable packet must be an object.');\n assertAllowedKeys(\n value,\n ['goal', 'constraints', 'decisions', 'verifiedFindings', 'inferredFindings', 'unresolvedQuestions', 'currentPlan'],\n 'Fable packet',\n );\n const packet: FablePlanPacket = {\n goal: boundedList(value.goal, 'goal'),\n constraints: boundedList(value.constraints, 'constraints', false),\n decisions: boundedList(value.decisions, 'decisions', false),\n verifiedFindings: boundedFindings(value.verifiedFindings),\n inferredFindings: boundedList(value.inferredFindings, 'inferredFindings', false),\n unresolvedQuestions: boundedList(value.unresolvedQuestions, 'unresolvedQuestions', false),\n ...(value.currentPlan === undefined ? {} : { currentPlan: boundedText(value.currentPlan, 'currentPlan', false) }),\n };\n if (Buffer.byteLength(JSON.stringify(packet), 'utf8') > MAX_FABLE_PACKET_BYTES) {\n throw new Error('Fable packet exceeds the bounded packet size.');\n }\n return packet;\n}\n\nfunction safeResult(result: FablePlanResult): FablePlanResult {\n const output = [result.draft, result.review].filter((value): value is string => value !== undefined).join('\\n');\n if (containsSuspectedCredential(output)) {\n return {\n operationId: result.operationId,\n status: 'failed',\n stage: 'failed',\n durationMs: result.durationMs,\n errorCode: 'unsafe_output',\n };\n }\n return result;\n}\n\nfunction timedOutResult(operationId: string, startedAt: number): FablePlanResult {\n return {\n operationId,\n status: 'timed_out',\n stage: 'interrupted',\n durationMs: Math.max(0, Date.now() - startedAt),\n errorCode: 'timeout',\n };\n}\n\nexport function createFablePlanFlow(options: FableFlowOptions): FablePlanFlow {\n let active:\n | {\n operationId: string;\n controller: AbortController;\n cancelSent: boolean;\n }\n | undefined;\n\n const cancel = (reason = 'Fable operation cancelled.'): void => {\n const current = active;\n if (!current) return;\n if (!current.cancelSent) {\n current.cancelSent = true;\n try {\n options.broker?.cancel(current.operationId, reason);\n } catch (error) {\n options.onError?.(error);\n }\n }\n current.controller.abort(new Error(reason));\n };\n\n const run = async (value: unknown, signal?: AbortSignal): Promise<FablePlanResult> => {\n if (active) throw new Error('A Fable operation is already active for this session.');\n if (!options.isAuthorized()) throw new Error('The Fable capability profile is not authorized.');\n const packet = sanitizeFablePacket(value);\n const operationId = `fable-${randomUUID()}`;\n const startedAt = Date.now();\n const controller = new AbortController();\n active = { operationId, controller, cancelSent: false };\n options.onStage?.('draft');\n\n const parentAbort = (): void => controller.abort(signal?.reason);\n if (signal) {\n signal.addEventListener('abort', parentAbort, { once: true });\n if (signal.aborted) parentAbort();\n }\n\n const brokerRequest: FablePlanRequest = {\n requester: FABLE_PLAN_REQUESTER,\n operationId,\n runtime: FABLE_PLAN_RUNTIME,\n model: FABLE_PLAN_MODEL,\n profile: FABLE_PLAN_PROFILE,\n packet,\n };\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timeoutTriggered = false;\n try {\n if (!options.broker) return timedOutResult(operationId, startedAt);\n const brokerResult = options.broker.start(brokerRequest, controller.signal);\n const cancelledResult = new Promise<FablePlanResult>((resolve) => {\n const onAbort = (): void => {\n if (timeoutTriggered) return;\n resolve({\n operationId,\n status: 'cancelled',\n stage: 'cancelled',\n durationMs: Math.max(0, Date.now() - startedAt),\n errorCode: 'cancelled',\n });\n };\n controller.signal.addEventListener('abort', onAbort, { once: true });\n });\n const timeoutResult =\n options.timeoutMs === undefined\n ? undefined\n : new Promise<FablePlanResult>((resolve) => {\n timeout = setTimeout(() => {\n timeoutTriggered = true;\n cancel('Fable operation timed out.');\n resolve(timedOutResult(operationId, startedAt));\n }, options.timeoutMs);\n });\n const result =\n timeoutResult === undefined\n ? await Promise.race([brokerResult, cancelledResult])\n : await Promise.race([brokerResult, timeoutResult, cancelledResult]);\n const safe = safeResult(result);\n options.onStage?.(\n safe.status === 'completed' ? 'completed' : safe.status === 'cancelled' ? 'cancelled' : safe.stage,\n );\n return safe;\n } catch (error) {\n options.onError?.(error);\n const failure: FablePlanResult = {\n operationId,\n status: 'failed',\n stage: 'failed',\n durationMs: Math.max(0, Date.now() - startedAt),\n errorCode: 'unavailable',\n };\n options.onStage?.('failed');\n return failure;\n } finally {\n if (timeout) clearTimeout(timeout);\n if (signal) signal.removeEventListener('abort', parentAbort);\n active = undefined;\n }\n };\n\n return {\n run,\n cancel,\n isActive: () => active !== undefined,\n };\n}\n"],"mappings":"sGAGA,MACa,EAAuB,yBACvB,EAAqB,SACrB,EAAmB,QACnB,EAAqB,uBAK5B,EAAkB,CACtB,4GACA,sCACA,6BACA,mCACD,CAiED,SAAS,EAAS,EAAkD,CAClE,OAAO,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAG7E,SAAS,EAAoB,EAAwB,CACnD,IAAK,IAAM,KAAa,EAAO,CAC7B,IAAM,EAAO,EAAU,YAAY,EAAE,CACrC,GAAI,IAAS,IAAA,KAAc,GAAQ,IAAyB,IAAS,KAAmB,MAAO,GAEjG,MAAO,GAGT,SAAgB,EAA4B,EAAwB,CAClE,OAAO,EAAgB,KAAM,GAAY,EAAQ,KAAK,EAAM,CAAC,CAG/D,S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Q,OAAO,MAAM,EAAe,EAAW,OAAO,CACrE,EAAkB,IAAI,QAA0B,GAAY,CAWhE,EAAW,OAAO,iBAAiB,YAVP,CACtB,GACJ,EAAQ,CACN,cACA,OAAQ,YACR,MAAO,YACP,WAAY,KAAK,IAAI,EAAG,KAAK,KAAK,CAAG,EAAU,CAC/C,UAAW,YACZ,CAAC,EAEiD,CAAE,KAAM,GAAM,CAAC,EACpE,CACI,EACJ,EAAQ,YAAc,IAAA,GAClB,IAAA,GACA,IAAI,QAA0B,GAAY,CACxC,EAAU,eAAiB,CACzB,EAAmB,GACnB,EAAO,6BAA6B,CACpC,EAAQ,EAAe,EAAa,EAAU,CAAC,EAC9C,EAAQ,UAAU,EACrB,CAKF,EAAO,EAHX,IAAkB,IAAA,GACd,MAAM,QAAQ,KAAK,CAAC,EAAc,EAAgB,CAAC,CACnD,MAAM,QAAQ,KAAK,CAAC,EAAc,EAAe,EAAgB,CAAC,CACzC,CAI/B,OAHA,EAAQ,UACN,EAAK,SAAW,YAAc,YAAc,EAAK,SAAW,YAAc,YAAc,EAAK,MAC9F,CACM,QACA,EAAO,CACd,EAAQ,UAAU,EAAM,CACxB,IAAM,EAA2B,CAC/B,cACA,OAAQ,SACR,MAAO,SACP,WAAY,KAAK,IAAI,EAAG,KAAK,KAAK,CAAG,EAAU,CAC/C,UAAW,cACZ,CAED,OADA,EAAQ,UAAU,SAAS,CACpB,SACC,CACJ,GAAS,aAAa,EAAQ,CAC9B,GAAQ,EAAO,oBAAoB,QAAS,EAAY,CAC5D,EAAS,IAAA,KAMX,SACA,aAAgB,IAAW,IAAA,GAC5B"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
//#region src/services/plan/fableFlow.d.ts
|
|
2
|
+
declare const FABLE_PROVIDER_SOURCE = "@agimon-ai/doompi-team";
|
|
3
|
+
declare const FABLE_PLAN_REQUESTER = "@agimon-ai/doompi-plan";
|
|
4
|
+
declare const FABLE_PLAN_RUNTIME = "claude";
|
|
5
|
+
declare const FABLE_PLAN_MODEL = "fable";
|
|
6
|
+
declare const FABLE_PLAN_PROFILE = "claude/fable-plan-v1";
|
|
7
|
+
declare const MAX_FABLE_PACKET_BYTES: number;
|
|
8
|
+
declare const MAX_FABLE_TEXT_BYTES: number;
|
|
9
|
+
declare const MAX_FABLE_ARRAY_ITEMS = 24;
|
|
10
|
+
interface FablePlanFinding {
|
|
11
|
+
path: string;
|
|
12
|
+
finding: string;
|
|
13
|
+
}
|
|
14
|
+
interface FablePlanPacket {
|
|
15
|
+
goal: string[];
|
|
16
|
+
constraints: string[];
|
|
17
|
+
decisions: string[];
|
|
18
|
+
verifiedFindings: FablePlanFinding[];
|
|
19
|
+
inferredFindings: string[];
|
|
20
|
+
unresolvedQuestions: string[];
|
|
21
|
+
currentPlan?: string;
|
|
22
|
+
}
|
|
23
|
+
type FablePlanStatus = 'completed' | 'failed' | 'timed_out' | 'cancelled' | 'interrupted';
|
|
24
|
+
type FablePlanStage = 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';
|
|
25
|
+
interface FablePlanResult {
|
|
26
|
+
operationId: string;
|
|
27
|
+
status: FablePlanStatus;
|
|
28
|
+
stage: FablePlanStage;
|
|
29
|
+
draft?: string;
|
|
30
|
+
review?: string;
|
|
31
|
+
draftRunId?: string;
|
|
32
|
+
reviewRunId?: string;
|
|
33
|
+
durationMs: number;
|
|
34
|
+
errorCode?: string;
|
|
35
|
+
}
|
|
36
|
+
interface FablePlanRequest {
|
|
37
|
+
requester: typeof FABLE_PLAN_REQUESTER;
|
|
38
|
+
operationId: string;
|
|
39
|
+
runtime: typeof FABLE_PLAN_RUNTIME;
|
|
40
|
+
model: typeof FABLE_PLAN_MODEL;
|
|
41
|
+
profile: typeof FABLE_PLAN_PROFILE;
|
|
42
|
+
packet: FablePlanPacket;
|
|
43
|
+
}
|
|
44
|
+
interface FablePlanBroker {
|
|
45
|
+
start(request: FablePlanRequest, signal: AbortSignal): Promise<FablePlanResult>;
|
|
46
|
+
cancel(operationId: string, reason: string): void;
|
|
47
|
+
}
|
|
48
|
+
interface FableFlowOptions {
|
|
49
|
+
broker?: FablePlanBroker;
|
|
50
|
+
isAuthorized: () => boolean;
|
|
51
|
+
timeoutMs?: number;
|
|
52
|
+
onStage?: (stage: FableStage) => void;
|
|
53
|
+
onError?: (error: unknown) => void;
|
|
54
|
+
}
|
|
55
|
+
type FableStage = 'idle' | 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';
|
|
56
|
+
interface FablePlanFlow {
|
|
57
|
+
run(value: unknown, signal?: AbortSignal): Promise<FablePlanResult>;
|
|
58
|
+
cancel(reason?: string): void;
|
|
59
|
+
isActive(): boolean;
|
|
60
|
+
}
|
|
61
|
+
declare function containsSuspectedCredential(value: string): boolean;
|
|
62
|
+
declare function sanitizeFablePacket(value: unknown): FablePlanPacket;
|
|
63
|
+
declare function createFablePlanFlow(options: FableFlowOptions): FablePlanFlow;
|
|
64
|
+
//#endregion
|
|
65
|
+
export { FABLE_PLAN_MODEL, FABLE_PLAN_PROFILE, FABLE_PLAN_REQUESTER, FABLE_PLAN_RUNTIME, FABLE_PROVIDER_SOURCE, FableFlowOptions, FablePlanBroker, FablePlanFinding, FablePlanFlow, FablePlanPacket, FablePlanRequest, FablePlanResult, FablePlanStage, FablePlanStatus, FableStage, MAX_FABLE_ARRAY_ITEMS, MAX_FABLE_PACKET_BYTES, MAX_FABLE_TEXT_BYTES, containsSuspectedCredential, createFablePlanFlow, sanitizeFablePacket };
|
|
66
|
+
//# sourceMappingURL=fableFlow.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fableFlow.d.cts","names":[],"sources":["../../../src/services/plan/fableFlow.ts"],"mappings":";cAGa,qBAAA;AAAA,cACA,oBAAA;AAAA,cACA,kBAAA;AAAA,cACA,gBAAA;AAAA,cACA,kBAAA;AAAA,cACA,sBAAA;AAAA,cACA,oBAAA;AAAA,cACA,qBAAA;AAAA,UAYI,gBAAA;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ai/doompi-plan";
|
|
4
|
+
declare const FABLE_PLAN_RUNTIME = "claude";
|
|
5
|
+
declare const FABLE_PLAN_MODEL = "fable";
|
|
6
|
+
declare const FABLE_PLAN_PROFILE = "claude/fable-plan-v1";
|
|
7
|
+
declare const MAX_FABLE_PACKET_BYTES: number;
|
|
8
|
+
declare const MAX_FABLE_TEXT_BYTES: number;
|
|
9
|
+
declare const MAX_FABLE_ARRAY_ITEMS = 24;
|
|
10
|
+
interface FablePlanFinding {
|
|
11
|
+
path: string;
|
|
12
|
+
finding: string;
|
|
13
|
+
}
|
|
14
|
+
interface FablePlanPacket {
|
|
15
|
+
goal: string[];
|
|
16
|
+
constraints: string[];
|
|
17
|
+
decisions: string[];
|
|
18
|
+
verifiedFindings: FablePlanFinding[];
|
|
19
|
+
inferredFindings: string[];
|
|
20
|
+
unresolvedQuestions: string[];
|
|
21
|
+
currentPlan?: string;
|
|
22
|
+
}
|
|
23
|
+
type FablePlanStatus = 'completed' | 'failed' | 'timed_out' | 'cancelled' | 'interrupted';
|
|
24
|
+
type FablePlanStage = 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';
|
|
25
|
+
interface FablePlanResult {
|
|
26
|
+
operationId: string;
|
|
27
|
+
status: FablePlanStatus;
|
|
28
|
+
stage: FablePlanStage;
|
|
29
|
+
draft?: string;
|
|
30
|
+
review?: string;
|
|
31
|
+
draftRunId?: string;
|
|
32
|
+
reviewRunId?: string;
|
|
33
|
+
durationMs: number;
|
|
34
|
+
errorCode?: string;
|
|
35
|
+
}
|
|
36
|
+
interface FablePlanRequest {
|
|
37
|
+
requester: typeof FABLE_PLAN_REQUESTER;
|
|
38
|
+
operationId: string;
|
|
39
|
+
runtime: typeof FABLE_PLAN_RUNTIME;
|
|
40
|
+
model: typeof FABLE_PLAN_MODEL;
|
|
41
|
+
profile: typeof FABLE_PLAN_PROFILE;
|
|
42
|
+
packet: FablePlanPacket;
|
|
43
|
+
}
|
|
44
|
+
interface FablePlanBroker {
|
|
45
|
+
start(request: FablePlanRequest, signal: AbortSignal): Promise<FablePlanResult>;
|
|
46
|
+
cancel(operationId: string, reason: string): void;
|
|
47
|
+
}
|
|
48
|
+
interface FableFlowOptions {
|
|
49
|
+
broker?: FablePlanBroker;
|
|
50
|
+
isAuthorized: () => boolean;
|
|
51
|
+
timeoutMs?: number;
|
|
52
|
+
onStage?: (stage: FableStage) => void;
|
|
53
|
+
onError?: (error: unknown) => void;
|
|
54
|
+
}
|
|
55
|
+
type FableStage = 'idle' | 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';
|
|
56
|
+
interface FablePlanFlow {
|
|
57
|
+
run(value: unknown, signal?: AbortSignal): Promise<FablePlanResult>;
|
|
58
|
+
cancel(reason?: string): void;
|
|
59
|
+
isActive(): boolean;
|
|
60
|
+
}
|
|
61
|
+
declare function containsSuspectedCredential(value: string): boolean;
|
|
62
|
+
declare function sanitizeFablePacket(value: unknown): FablePlanPacket;
|
|
63
|
+
declare function createFablePlanFlow(options: FableFlowOptions): FablePlanFlow;
|
|
64
|
+
//#endregion
|
|
65
|
+
export { FABLE_PLAN_MODEL, FABLE_PLAN_PROFILE, FABLE_PLAN_REQUESTER, FABLE_PLAN_RUNTIME, FABLE_PROVIDER_SOURCE, FableFlowOptions, FablePlanBroker, FablePlanFinding, FablePlanFlow, FablePlanPacket, FablePlanRequest, FablePlanResult, FablePlanStage, FablePlanStatus, FableStage, MAX_FABLE_ARRAY_ITEMS, MAX_FABLE_PACKET_BYTES, MAX_FABLE_TEXT_BYTES, containsSuspectedCredential, createFablePlanFlow, sanitizeFablePacket };
|
|
66
|
+
//# sourceMappingURL=fableFlow.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fableFlow.d.mts","names":[],"sources":["../../../src/services/plan/fableFlow.ts"],"mappings":";cAGa,qBAAA;AAAA,cACA,oBAAA;AAAA,cACA,kBAAA;AAAA,cACA,gBAAA;AAAA,cACA,kBAAA;AAAA,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ompi-team`,r=`@agimon-ai/doompi-plan`,i=`claude`,a=`fable`,o=`claude/fable-plan-v1`,s=32*1024,c=4*1024,l=24,u=[/(?:api[_-]?key|access[_-]?token|client[_-]?secret|password|private[_-]?key|authorization|bearer)\s*[:=]/iu,/-----BEGIN [A-Z ]*PRIVATE KEY-----/u,/\bsk-[A-Za-z0-9_-]{16,}\b/u,/\bgh[pousr]_[A-Za-z0-9_]{16,}\b/u];function d(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function f(e){for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(e<=31||e===127))return!0}return!1}function p(e){return u.some(t=>t.test(e))}function m(t,n,r=!0){if(typeof t!=`string`)throw Error(`${n} must be a string.`);let i=t.trim();if(!i&&r)throw Error(`${n} must not be empty.`);if(e.byteLength(i,`utf8`)>4096||f(i))throw Error(`${n} exceeds the bounded Fable text limit or contains control characters.`);if(p(i))throw Error(`${n} appears to contain a credential.`);return i}function h(e,t,n=!0){if(!Array.isArray(e))throw Error(`${t} must be an array.`);if(e.length>24)throw Error(`${t} exceeds the bounded item limit.`);let r=e.map((e,n)=>m(e,`${t}[${n}]`));if(n&&r.length===0)throw Error(`${t} must contain at least one item.`);return r}function g(e,t){if(typeof e!=`string`)throw Error(`${t} must be a string.`);let n=e.trim();if(!n||n.length>512||f(n))throw Error(`${t} is not a safe source path.`);if(p(n))throw Error(`${t} appears to contain a credential.`);return n}function _(e){if(!Array.isArray(e))throw Error(`verifiedFindings must be an array.`);if(e.length>24)throw Error(`verifiedFindings exceeds the bounded item limit.`);return e.map((e,t)=>{if(!d(e))throw Error(`verifiedFindings[${t}] must be an object.`);if(Object.keys(e).some(e=>e!==`path`&&e!==`finding`))throw Error(`verifiedFindings[${t}] contains an unsupported field.`);return{path:g(e.path,`verifiedFindings[${t}].path`),finding:m(e.finding,`verifiedFindings[${t}].finding`)}})}function v(e,t,n){let r=new Set(t),i=Object.keys(e).find(e=>!r.has(e));if(i)throw Error(`${n} contains unsupported field '${i}'.`)}function y(t){if(!d(t))throw Error(`Fable packet must be an object.`);v(t,[`goal`,`constraints`,`decisions`,`verifiedFindings`,`inferredFindings`,`unresolvedQuestions`,`currentPlan`],`Fable packet`);let n={goal:h(t.goal,`goal`),constraints:h(t.constraints,`constraints`,!1),decisions:h(t.decisions,`decisions`,!1),verifiedFindings:_(t.verifiedFindings),inferredFindings:h(t.inferredFindings,`inferredFindings`,!1),unresolvedQuestions:h(t.unresolvedQuestions,`unresolvedQuestions`,!1),...t.currentPlan===void 0?{}:{currentPlan:m(t.currentPlan,`currentPlan`,!1)}};if(e.byteLength(JSON.stringify(n),`utf8`)>32768)throw Error(`Fable packet exceeds the bounded packet size.`);return n}function b(e){return p([e.draft,e.review].filter(e=>e!==void 0).join(`
|
|
2
|
+
`))?{operationId:e.operationId,status:`failed`,stage:`failed`,durationMs:e.durationMs,errorCode:`unsafe_output`}:e}function x(e,t){return{operationId:e,status:`timed_out`,stage:`interrupted`,durationMs:Math.max(0,Date.now()-t),errorCode:`timeout`}}function S(e){let n,s=(t=`Fable operation cancelled.`)=>{let r=n;if(r){if(!r.cancelSent){r.cancelSent=!0;try{e.broker?.cancel(r.operationId,t)}catch(t){e.onError?.(t)}}r.controller.abort(Error(t))}};return{run:async(c,l)=>{if(n)throw Error(`A Fable operation is already active for this session.`);if(!e.isAuthorized())throw Error(`The Fable capability profile is not authorized.`);let u=y(c),d=`fable-${t()}`,f=Date.now(),p=new AbortController;n={operationId:d,controller:p,cancelSent:!1},e.onStage?.(`draft`);let m=()=>p.abort(l?.reason);l&&(l.addEventListener(`abort`,m,{once:!0}),l.aborted&&m());let h={requester:r,operationId:d,runtime:i,model:a,profile:o,packet:u},g,_=!1;try{if(!e.broker)return x(d,f);let t=e.broker.start(h,p.signal),n=new Promise(e=>{p.signal.addEventListener(`abort`,()=>{_||e({operationId:d,status:`cancelled`,stage:`cancelled`,durationMs:Math.max(0,Date.now()-f),errorCode:`cancelled`})},{once:!0})}),r=e.timeoutMs===void 0?void 0:new Promise(t=>{g=setTimeout(()=>{_=!0,s(`Fable operation timed out.`),t(x(d,f))},e.timeoutMs)}),i=b(r===void 0?await Promise.race([t,n]):await Promise.race([t,r,n]));return e.onStage?.(i.status===`completed`?`completed`:i.status===`cancelled`?`cancelled`:i.stage),i}catch(t){e.onError?.(t);let n={operationId:d,status:`failed`,stage:`failed`,durationMs:Math.max(0,Date.now()-f),errorCode:`unavailable`};return e.onStage?.(`failed`),n}finally{g&&clearTimeout(g),l&&l.removeEventListener(`abort`,m),n=void 0}},cancel:s,isActive:()=>n!==void 0}}export{a as FABLE_PLAN_MODEL,o as FABLE_PLAN_PROFILE,r as FABLE_PLAN_REQUESTER,i as FABLE_PLAN_RUNTIME,n as FABLE_PROVIDER_SOURCE,l as MAX_FABLE_ARRAY_ITEMS,s as MAX_FABLE_PACKET_BYTES,c as MAX_FABLE_TEXT_BYTES,p as containsSuspectedCredential,S as createFablePlanFlow,y as sanitizeFablePacket};
|
|
3
|
+
//# sourceMappingURL=fableFlow.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fableFlow.mjs","names":[],"sources":["../../../src/services/plan/fableFlow.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { randomUUID } from 'node:crypto';\n\nexport const FABLE_PROVIDER_SOURCE = '@agimon-ai/doompi-team';\nexport const FABLE_PLAN_REQUESTER = '@agimon-ai/doompi-plan';\nexport const FABLE_PLAN_RUNTIME = 'claude';\nexport const FABLE_PLAN_MODEL = 'fable';\nexport const FABLE_PLAN_PROFILE = 'claude/fable-plan-v1';\nexport const MAX_FABLE_PACKET_BYTES = 32 * 1024;\nexport const MAX_FABLE_TEXT_BYTES = 4 * 1024;\nexport const MAX_FABLE_ARRAY_ITEMS = 24;\n\nconst SECRET_PATTERNS = [\n /(?:api[_-]?key|access[_-]?token|client[_-]?secret|password|private[_-]?key|authorization|bearer)\\s*[:=]/iu,\n /-----BEGIN [A-Z ]*PRIVATE KEY-----/u,\n /\\bsk-[A-Za-z0-9_-]{16,}\\b/u,\n /\\bgh[pousr]_[A-Za-z0-9_]{16,}\\b/u,\n];\nconst CONTROL_CHARACTER_MAX = 31;\nconst DELETE_CHARACTER = 127;\nconst MAX_SOURCE_PATH_LENGTH = 512;\n\nexport interface FablePlanFinding {\n path: string;\n finding: string;\n}\n\nexport interface FablePlanPacket {\n goal: string[];\n constraints: string[];\n decisions: string[];\n verifiedFindings: FablePlanFinding[];\n inferredFindings: string[];\n unresolvedQuestions: string[];\n currentPlan?: string;\n}\n\nexport type FablePlanStatus = 'completed' | 'failed' | 'timed_out' | 'cancelled' | 'interrupted';\nexport type FablePlanStage = 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';\n\nexport interface FablePlanResult {\n operationId: string;\n status: FablePlanStatus;\n stage: FablePlanStage;\n draft?: string;\n review?: string;\n draftRunId?: string;\n reviewRunId?: string;\n durationMs: number;\n errorCode?: string;\n}\n\nexport interface FablePlanRequest {\n requester: typeof FABLE_PLAN_REQUESTER;\n operationId: string;\n runtime: typeof FABLE_PLAN_RUNTIME;\n model: typeof FABLE_PLAN_MODEL;\n profile: typeof FABLE_PLAN_PROFILE;\n packet: FablePlanPacket;\n}\n\nexport interface FablePlanBroker {\n start(request: FablePlanRequest, signal: AbortSignal): Promise<FablePlanResult>;\n cancel(operationId: string, reason: string): void;\n}\n\nexport interface FableFlowOptions {\n broker?: FablePlanBroker;\n isAuthorized: () => boolean;\n timeoutMs?: number;\n onStage?: (stage: FableStage) => void;\n onError?: (error: unknown) => void;\n}\n\nexport type FableStage = 'idle' | 'draft' | 'review' | 'completed' | 'failed' | 'cancelled' | 'interrupted';\n\nexport interface FablePlanFlow {\n run(value: unknown, signal?: AbortSignal): Promise<FablePlanResult>;\n cancel(reason?: string): void;\n isActive(): boolean;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (const character of value) {\n const code = character.codePointAt(0);\n if (code !== undefined && (code <= CONTROL_CHARACTER_MAX || code === DELETE_CHARACTER)) return true;\n }\n return false;\n}\n\nexport function containsSuspectedCredential(value: string): boolean {\n return SECRET_PATTERNS.some((pattern) => pattern.test(value));\n}\n\nfunction boundedText(value: unknown, field: string, required = true): string {\n if (typeof value !== 'string') throw new Error(`${field} must be a string.`);\n const text = value.trim();\n if (!text && required) throw new Error(`${field} must not be empty.`);\n if (Buffer.byteLength(text, 'utf8') > MAX_FABLE_TEXT_BYTES || hasControlCharacter(text)) {\n throw new Error(`${field} exceeds the bounded Fable text limit or contains control characters.`);\n }\n if (containsSuspectedCredential(text)) throw new Error(`${field} appears to contain a credential.`);\n return text;\n}\n\nfunction boundedList(value: unknown, field: string, required = true): string[] {\n if (!Array.isArray(value)) throw new Error(`${field} must be an array.`);\n if (value.length > MAX_FABLE_ARRAY_ITEMS) throw new Error(`${field} exceeds the bounded item limit.`);\n const items = value.map((item, index) => boundedText(item, `${field}[${index}]`));\n if (required && items.length === 0) throw new Error(`${field} must contain at least one item.`);\n return items;\n}\n\nfunction boundedPath(value: unknown, field: string): string {\n if (typeof value !== 'string') throw new Error(`${field} must be a string.`);\n const sourcePath = value.trim();\n if (!sourcePath || sourcePath.length > MAX_SOURCE_PATH_LENGTH || hasControlCharacter(sourcePath)) {\n throw new Error(`${field} is not a safe source path.`);\n }\n if (containsSuspectedCredential(sourcePath)) throw new Error(`${field} appears to contain a credential.`);\n return sourcePath;\n}\n\nfunction boundedFindings(value: unknown): FablePlanFinding[] {\n if (!Array.isArray(value)) throw new Error('verifiedFindings must be an array.');\n if (value.length > MAX_FABLE_ARRAY_ITEMS) throw new Error('verifiedFindings exceeds the bounded item limit.');\n return value.map((item, index) => {\n if (!isRecord(item)) throw new Error(`verifiedFindings[${index}] must be an object.`);\n const keys = Object.keys(item);\n if (keys.some((key) => key !== 'path' && key !== 'finding')) {\n throw new Error(`verifiedFindings[${index}] contains an unsupported field.`);\n }\n return {\n path: boundedPath(item.path, `verifiedFindings[${index}].path`),\n finding: boundedText(item.finding, `verifiedFindings[${index}].finding`),\n };\n });\n}\n\nfunction assertAllowedKeys(value: Record<string, unknown>, keys: readonly string[], field: string): void {\n const allowed = new Set(keys);\n const unexpected = Object.keys(value).find((key) => !allowed.has(key));\n if (unexpected) throw new Error(`${field} contains unsupported field '${unexpected}'.`);\n}\n\nexport function sanitizeFablePacket(value: unknown): FablePlanPacket {\n if (!isRecord(value)) throw new Error('Fable packet must be an object.');\n assertAllowedKeys(\n value,\n ['goal', 'constraints', 'decisions', 'verifiedFindings', 'inferredFindings', 'unresolvedQuestions', 'currentPlan'],\n 'Fable packet',\n );\n const packet: FablePlanPacket = {\n goal: boundedList(value.goal, 'goal'),\n constraints: boundedList(value.constraints, 'constraints', false),\n decisions: boundedList(value.decisions, 'decisions', false),\n verifiedFindings: boundedFindings(value.verifiedFindings),\n inferredFindings: boundedList(value.inferredFindings, 'inferredFindings', false),\n unresolvedQuestions: boundedList(value.unresolvedQuestions, 'unresolvedQuestions', false),\n ...(value.currentPlan === undefined ? {} : { currentPlan: boundedText(value.currentPlan, 'currentPlan', false) }),\n };\n if (Buffer.byteLength(JSON.stringify(packet), 'utf8') > MAX_FABLE_PACKET_BYTES) {\n throw new Error('Fable packet exceeds the bounded packet size.');\n }\n return packet;\n}\n\nfunction safeResult(result: FablePlanResult): FablePlanResult {\n const output = [result.draft, result.review].filter((value): value is string => value !== undefined).join('\\n');\n if (containsSuspectedCredential(output)) {\n return {\n operationId: result.operationId,\n status: 'failed',\n stage: 'failed',\n durationMs: result.durationMs,\n errorCode: 'unsafe_output',\n };\n }\n return result;\n}\n\nfunction timedOutResult(operationId: string, startedAt: number): FablePlanResult {\n return {\n operationId,\n status: 'timed_out',\n stage: 'interrupted',\n durationMs: Math.max(0, Date.now() - startedAt),\n errorCode: 'timeout',\n };\n}\n\nexport function createFablePlanFlow(options: FableFlowOptions): FablePlanFlow {\n let active:\n | {\n operationId: string;\n controller: AbortController;\n cancelSent: boolean;\n }\n | undefined;\n\n const cancel = (reason = 'Fable operation cancelled.'): void => {\n const current = active;\n if (!current) return;\n if (!current.cancelSent) {\n current.cancelSent = true;\n try {\n options.broker?.cancel(current.operationId, reason);\n } catch (error) {\n options.onError?.(error);\n }\n }\n current.controller.abort(new Error(reason));\n };\n\n const run = async (value: unknown, signal?: AbortSignal): Promise<FablePlanResult> => {\n if (active) throw new Error('A Fable operation is already active for this session.');\n if (!options.isAuthorized()) throw new Error('The Fable capability profile is not authorized.');\n const packet = sanitizeFablePacket(value);\n const operationId = `fable-${randomUUID()}`;\n const startedAt = Date.now();\n const controller = new AbortController();\n active = { operationId, controller, cancelSent: false };\n options.onStage?.('draft');\n\n const parentAbort = (): void => controller.abort(signal?.reason);\n if (signal) {\n signal.addEventListener('abort', parentAbort, { once: true });\n if (signal.aborted) parentAbort();\n }\n\n const brokerRequest: FablePlanRequest = {\n requester: FABLE_PLAN_REQUESTER,\n operationId,\n runtime: FABLE_PLAN_RUNTIME,\n model: FABLE_PLAN_MODEL,\n profile: FABLE_PLAN_PROFILE,\n packet,\n };\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timeoutTriggered = false;\n try {\n if (!options.broker) return timedOutResult(operationId, startedAt);\n const brokerResult = options.broker.start(brokerRequest, controller.signal);\n const cancelledResult = new Promise<FablePlanResult>((resolve) => {\n const onAbort = (): void => {\n if (timeoutTriggered) return;\n resolve({\n operationId,\n status: 'cancelled',\n stage: 'cancelled',\n durationMs: Math.max(0, Date.now() - startedAt),\n errorCode: 'cancelled',\n });\n };\n controller.signal.addEventListener('abort', onAbort, { once: true });\n });\n const timeoutResult =\n options.timeoutMs === undefined\n ? undefined\n : new Promise<FablePlanResult>((resolve) => {\n timeout = setTimeout(() => {\n timeoutTriggered = true;\n cancel('Fable operation timed out.');\n resolve(timedOutResult(operationId, startedAt));\n }, options.timeoutMs);\n });\n const result =\n timeoutResult === undefined\n ? await Promise.race([brokerResult, cancelledResult])\n : await Promise.race([brokerResult, timeoutResult, cancelledResult]);\n const safe = safeResult(result);\n options.onStage?.(\n safe.status === 'completed' ? 'completed' : safe.status === 'cancelled' ? 'cancelled' : safe.stage,\n );\n return safe;\n } catch (error) {\n options.onError?.(error);\n const failure: FablePlanResult = {\n operationId,\n status: 'failed',\n stage: 'failed',\n durationMs: Math.max(0, Date.now() - startedAt),\n errorCode: 'unavailable',\n };\n options.onStage?.('failed');\n return failure;\n } finally {\n if (timeout) clearTimeout(timeout);\n if (signal) signal.removeEventListener('abort', parentAbort);\n active = undefined;\n }\n };\n\n return {\n run,\n cancel,\n isActive: () => active !== undefined,\n };\n}\n"],"mappings":"8EAGA,MAAa,EAAwB,yBACxB,EAAuB,yBACvB,EAAqB,SACrB,EAAmB,QACnB,EAAqB,uBACrB,EAAyB,GAAK,KAC9B,EAAuB,EAAI,KAC3B,EAAwB,GAE/B,EAAkB,CACtB,4GACA,sCACA,6BACA,mCACD,CAiED,SAAS,EAAS,EAAkD,CAClE,OAAO,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAG7E,SAAS,EAAoB,EAAwB,CACnD,IAAK,IAAM,KAAa,EAAO,CAC7B,IAAM,EAAO,EAAU,YAAY,EAAE,CACrC,GAAI,IAAS,IAAA,KAAc,GAAQ,IAAyB,IAAS,KAAmB,MAAO,GAEjG,MAAO,GAGT,SAAgB,EAA4B,EAAwB,CAClE,OAAO,EAAgB,KAAM,GAAY,EAAQ,KAAK,EAAM,CAAC,CAG/D,SAAS,EAAY,EAAgB,EAAe,EAAW,GAAc,CAC3E,GAAI,OAAO,GAAU,SAAU,MAAU,MAAM,GAAG,EAAM,oBAAoB,CAC5E,IAAM,EAAO,EAAM,MAAM,CACzB,GAAI,CAAC,GAAQ,EAAU,MAAU,MAAM,GAAG,EAAM,qBAAqB,CACrE,GAAI,EAAO,WAAW,EAAM,OAAO,CAAA,MAA2B,EAAoB,EAAK,CACrF,MAAU,MAAM,GAAG,EAAM,uEAAuE,CAElG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xC,EAAU,eAAiB,CACzB,EAAmB,GACnB,EAAO,6BAA6B,CACpC,EAAQ,EAAe,EAAa,EAAU,CAAC,EAC9C,EAAQ,UAAU,EACrB,CAKF,EAAO,EAHX,IAAkB,IAAA,GACd,MAAM,QAAQ,KAAK,CAAC,EAAc,EAAgB,CAAC,CACnD,MAAM,QAAQ,KAAK,CAAC,EAAc,EAAe,EAAgB,CAAC,CACzC,CAI/B,OAHA,EAAQ,UACN,EAAK,SAAW,YAAc,YAAc,EAAK,SAAW,YAAc,YAAc,EAAK,MAC9F,CACM,QACA,EAAO,CACd,EAAQ,UAAU,EAAM,CACxB,IAAM,EAA2B,CAC/B,cACA,OAAQ,SACR,MAAO,SACP,WAAY,KAAK,IAAI,EAAG,KAAK,KAAK,CAAG,EAAU,CAC/C,UAAW,cACZ,CAED,OADA,EAAQ,UAAU,SAAS,CACpB,SACC,CACJ,GAAS,aAAa,EAAQ,CAC9B,GAAQ,EAAO,oBAAoB,QAAS,EAAY,CAC5D,EAAS,IAAA,KAMX,SACA,aAAgB,IAAW,IAAA,GAC5B"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
const e=require(`../../_virtual/_rolldown/runtime.cjs`),t=require(`../../schemas/plan/config.cjs`),n=require(`./fableFlow.cjs`),r=require(`../../adapters/telemetry/logSinkTelemetry.cjs`),i=require(`../../schemas/plan/planConfig.cjs`),a=require(`./prompts.cjs`);let o=require(`@agimon-ai/doompi-config`),s=require(`node:buffer`),c=require(`node:crypto`),l=require(`node:fs`);l=e.__toESM(l,1);let ee=require(`node:os`);ee=e.__toESM(ee,1);let te=require(`node:path`);te=e.__toESM(te,1);let u=require(`@agimon-ai/doompi-config/configWriter`),d=require(`@agimon-ai/doompi-extension-contracts/fable-plan`),f=require(`@agimon-ai/doompi-extension-contracts/mode`),ne=require(`@agimon-ai/doompi-extension-contracts/protocol`),p=require(`@agimon-ai/doompi-extension-contracts/subagent-policy`),m=require(`@agimon-ai/doompi-extension-contracts/subagent-tool`),h=require(`@agimon-ai/doompi-extension-contracts/voice-tools`),g=require(`@agimon-ai/doompi-ui/config`),_=require(`@agimon-ai/doompi-ui/leader`),v=require(`@agimon-ai/doompi-user-feedback/voice-question-handoff`);const y=`agent-harness-plan-mode`,re=`agent-harness-plan-document`,b=`complete_plan`,x=`write_plan`,S=`ask_user_question`,C=`bash`,w=`find`,T=`grep`,E=`read`,ie=`subagent`,ae=`task`,oe=`record_debug_evidence`,D=`run_fable_plan`,O=`implementation-plan`,k=`@agimon-ai/doompi-plan`,se=`activate`,ce=`deactivate`,A=`warning`,le=`info`,ue=`Refused to write the plan because its destination is not a regular file.`,j=`plan.trigger`,de=`plan.model`,M=`plan.flavor`,fe=`not_found`,pe=`unauthenticated`,me=`restore_failed`,he=new Set,ge=5e3,_e=`Exit plan mode and start implementation`,ve=`Continue planning`,N=`exit`,ye=`continue`,be={questions:[{question:`Plan complete. What would you like to do?`,header:`Plan review`,options:[{label:_e,description:`Leave read-only plan mode and begin implementing the approved plan.`},{label:ve,description:`Remain in read-only plan mode and refine the implementation plan.`}]}]},xe=new Set([`add_directory`,S,C,b,w,T,`intercom`,`ls`,f.MINOR_MODE_TOOL_NAME,...h.VOICE_MODE_TOOL_NAMES,E,`search_external_files`,ie,`subagent_supervisor`,`subagent_wait`,ae,x]),P=new Set([`edit`,`write`,`mcp`]),F=[E,C,T,w,`ls`],Se=[...F,`mcp`],I=`leader`,Ce=`voice_tool`,L=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],R=[`idle`,`draft`,`review`,`completed`,`failed`,`cancelled`,`interrupted`],we=`@agimon-ai/doompi-plan`,z={type:`string`,enum:[...[`normal`,`debug`,`fable`]]},Te={type:`object`,properties:{flavor:z},required:[`flavor`],additionalProperties:!1},Ee={type:`object`,properties:{},additionalProperties:!1},De={type:`object`,properties:{active:{type:`boolean`},flavor:{anyOf:[{...z},{type:`null`}]},changed:{type:`boolean`}},required:[`active`,`flavor`,`changed`],additionalProperties:!1},B=new Set([b,x,oe,D,f.MINOR_MODE_TOOL_NAME,...h.VOICE_MODE_TOOL_NAMES]);function Oe(e){return(e.match(/^#\s+(.+?)\s*$/m)?.[1]??O).normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64)||O}function ke(e){return`${encodeURIComponent(e).slice(0,48)||`session`}--${(0,c.createHash)(`sha256`).update(e).digest(`hex`)}`}function Ae(e=new Date,t=(0,c.randomUUID)()){return`${e.toISOString().replace(/[-:]/g,``).replace(/\.\d{3}Z$/,`Z`)}--${t}`}function je(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(!r||typeof r!=`object`)continue;let i=r;if(i.type!==`message`||i.message?.role!==`assistant`||!Array.isArray(i.message.content))continue;let a=i.message.content.findIndex(e=>{if(!e||typeof e!=`object`)return!1;let n=e;return n.type===`toolCall`&&n.id===t&&n.name===x});if(!(a<0))return i.message.content.slice(0,a).flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return t.type===`text`&&typeof t.text==`string`?[t.text]:[]}).join(`
|
|
2
|
+
|
|
3
|
+
`).trim()||void 0}}function Me(e){return e.reason instanceof Error?e.reason:Error(`Plan write cancelled.`)}async function V(e,t){if(t.aborted)throw Me(t);let n,r=new Promise((e,r)=>{n=()=>r(Me(t)),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e){return typeof e==`string`}function W(e){if(!(!H(e)||!U(e.provider)||!U(e.id))&&!(!e.provider||!e.id||e.provider.length>128||e.id.length>128))return{provider:e.provider,id:e.id}}function G(e){return U(e)&&L.includes(e)?e:void 0}function K(e){return U(e)&&R.includes(e)?e:void 0}function Ne(e){if(!(!Array.isArray(e)||e.some(e=>!U(e))))return e.map(e=>e)}function q(e){if(!H(e))return;let t=Ne(e.tools),n=G(e.thinking);if(!t||n===void 0)return;let r=e.model===void 0?void 0:W(e.model);if(!(e.model!==void 0&&!r))return{tools:t,...r?{model:r}:{},thinking:n}}function Pe(e){return e===`normal`||e===`debug`||e===`fable`?e:void 0}function Fe(e){if(e.version!==2)return;let t=e.activeFlavor===void 0?void 0:Pe(e.activeFlavor);if(e.activeFlavor!==void 0&&!t)return;let n=e.originalSnapshot===void 0?void 0:q(e.originalSnapshot);if(e.originalSnapshot!==void 0&&!n)return;let r=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(e.planId!==void 0&&r===void 0)return;let i=e.interruptedFableStage===void 0?void 0:K(e.interruptedFableStage);if(!(e.interruptedFableStage!==void 0&&!i))return{version:2,...t?{activeFlavor:t}:{},...n?{originalSnapshot:n}:{},...r?{planId:r}:{},...i?{interruptedFableStage:i}:{}}}function Ie(e){if(e.enabled!==!0&&e.enabled!==!1)return;let t=e.toolsBeforePlanMode===void 0?void 0:Ne(e.toolsBeforePlanMode);if(e.toolsBeforePlanMode!==void 0&&!t)return;let n=e.modelBeforePlanMode===void 0?void 0:W(e.modelBeforePlanMode);if(e.modelBeforePlanMode!==void 0&&!n)return;let r=e.thinkingBeforePlanMode===void 0?void 0:G(e.thinkingBeforePlanMode);if(e.thinkingBeforePlanMode!==void 0&&r===void 0)return;let i=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(e.planId!==void 0&&i===void 0)return;let a=t&&r!==void 0?{tools:t,...n?{model:n}:{},thinking:r}:void 0;return{version:2,...e.enabled?{activeFlavor:`normal`}:{},...a?{originalSnapshot:a}:{},...i?{planId:i}:{}}}function Le(e){if(H(e))return Fe(e)??Ie(e)}function Re(e){if(!H(e)||!U(e.content)||!U(e.path)||!U(e.sessionId)||!U(e.title)||!U(e.writtenAt))return;let t=e.planId===void 0?void 0:U(e.planId)?e.planId:void 0;if(!(e.planId!==void 0&&t===void 0))return{content:e.content,path:e.path,sessionId:e.sessionId,...t?{planId:t}:{},title:e.title,writtenAt:e.writtenAt}}function ze(e,t,n){if(!U(e))throw Error(`${t} must be a string.`);let r=e.trim();if(n&&!r)throw Error(`${t} must not be empty.`);if(s.Buffer.byteLength(r,`utf8`)>4096)throw Error(`${t} exceeds the bounded debug evidence limit.`);return r}function Be(e,t){if(!Array.isArray(e)||e.length>32)throw Error(`${t} must be a bounded string array.`);return e.map((e,n)=>ze(e,`${t}[${n}]`,!1))}function Ve(e,t){return e===void 0?``:ze(e,t,!1)}function J(e,t){return e===void 0?[]:Be(e,t)}function He(e,t,n){let r=new Set(t),i=Object.keys(e).find(e=>!r.has(e));if(i)throw Error(`${n} contains unsupported field '${i}'.`)}function Ue(e){if(!H(e))throw Error(`Debug evidence must be an object.`);He(e,[`issue`,`expectedBehavior`,`reproductionAttempt`,`actualBehavior`,`logs`,`correlatedTraceEvidence`,`processOutput`,`browserConsoleEvidence`,`correlationIds`,`timestamps`,`verifiedFacts`,`hypotheses`,`unavailableEvidence`],`Debug evidence`);let t={issue:ze(e.issue,`issue`,!0),expectedBehavior:Ve(e.expectedBehavior,`expectedBehavior`),reproductionAttempt:Ve(e.reproductionAttempt,`reproductionAttempt`),actualBehavior:Ve(e.actualBehavior,`actualBehavior`),logs:J(e.logs,`logs`),correlatedTraceEvidence:J(e.correlatedTraceEvidence,`correlatedTraceEvidence`),processOutput:J(e.processOutput,`processOutput`),browserConsoleEvidence:J(e.browserConsoleEvidence,`browserConsoleEvidence`),correlationIds:J(e.correlationIds,`correlationIds`),timestamps:J(e.timestamps,`timestamps`),verifiedFacts:J(e.verifiedFacts,`verifiedFacts`),hypotheses:J(e.hypotheses,`hypotheses`),unavailableEvidence:J(e.unavailableEvidence,`unavailableEvidence`)};if(s.Buffer.byteLength(JSON.stringify(t),`utf8`)>32768)throw Error(`Debug evidence exceeds the bounded packet size.`);return t}function We(e,t){let n=new Set(t),r=e.filter(e=>xe.has(e)&&n.has(e)),i=e.filter(e=>!xe.has(e)&&!P.has(e)&&!B.has(e)&&n.has(e)),a=F.filter(e=>n.has(e)),o=[b,ae,x].filter(e=>n.has(e));return[...new Set([...r,...i,...a,...o])]}function Ge(e,t,n,r,i){let a=new Set(n),o=t.filter(e=>!xe.has(e)&&!P.has(e)&&!B.has(e)),s=We([...new Set([...e,...o])].filter(e=>!B.has(e)),n),c=r===`debug`?[oe,...i].filter(e=>a.has(e)):[];r===`fable`&&a.has(D)&&c.push(D);for(let e of[f.MINOR_MODE_TOOL_NAME,...h.VOICE_MODE_TOOL_NAMES])t.includes(e)&&a.has(e)&&c.push(e);return[...new Set([...s,...c])]}function Ke(e,t,n){let r=new Set(n),i=new Set(t),a=e.filter(e=>!B.has(e)&&r.has(e)&&(e!==S||i.has(e))),o=t.filter(e=>!xe.has(e)&&!P.has(e)&&!B.has(e)&&r.has(e)),s=[f.MINOR_MODE_TOOL_NAME,...h.VOICE_MODE_TOOL_NAMES].filter(e=>i.has(e)&&r.has(e));return[...new Set([...a,...o,...s])]}function Y(e){if(e.output=!1,e.progress=!1,e.worktree=!1,Array.isArray(e.parallel))for(let t of e.parallel)Y(t);else e.parallel&&Y(e.parallel)}function qe(e){if(e.action!==void 0){(0,m.isSubagentAction)(e.action)&&(0,m.subagentActionAcceptsField)(e.action,`artifacts`)&&(e.artifacts=!1);return}e.artifacts=!1,e.output=!1,e.share=!1,e.progress=!1,e.worktree=!1,delete e.chainDir,delete e.outputSchema,delete e.sessionDir;for(let t of e.tasks??[])Y(t);for(let t of e.chain??[])Y(t)}function Je(e,t){if(!e?.model&&!e?.thinking)return;let n=e.model??(t?`${t.provider}/${t.id}`:void 0);if(n)return e.thinking?`${n.replace(/:(?:off|minimal|low|medium|high|xhigh|max)$/,``)}:${e.thinking}`:n}function Ye(e,t){if(e.action===`run`)for(let n of e.requests??[])n.model=t}function Xe(e,t){if(e.action===`assign`)for(let n of e.assignments??[])n.model=t}function Ze(e){return new Set([`append-step`,`create`,`delete`,`disable`,`eject`,`enable`,`grant-spawn-budget`,`reset`,`schedule`,`schedule-cancel`,`update`,`watchdog.configure`]).has(e??``)}function Qe(e,t){let n=e.indexOf(`/`);if(n>0)return t.modelRegistry.find(e.slice(0,n),e.slice(n+1));let r=t.modelRegistry.getAvailable().filter(t=>t.id===e);return r.find(e=>e.provider===t.model?.provider)??(r.length===1?r[0]:void 0)}function $e(e=process.env,n=process.cwd()){return t.loadDoomConfig((0,o.loadHarnessState)(e).state.root??n).modes?.planning}function et(e){let t={key:`p`,label:`plan`,order:60};return[{id:`plan.normal`,path:[t,{key:`p`,label:`normal`,detail:`read-only planning`}],action:{name:`plan.normal`}},{id:`plan.debug`,path:[t,{key:`d`,label:`debug`,detail:`adaptive debug planning`}],action:{name:`plan.debug`}},{id:`plan.fable`,path:[t,{key:`f`,label:`fable`,detail:`repository-aware draft`}],action:{name:`plan.fable`}},...e?[{id:`plan.exit`,path:[t,{key:`e`,label:`exit`,detail:`restore and exit`}],action:{name:`plan.exit`}}]:[]]}function X(e,t=$e,c=r.createPlanTelemetry(),m={}){let S=!1,w,T,E,O,P,F,L=!1,R=!1,z,B,U=`idle`,W,G,K,Ne=Promise.resolve(),q=m.doomIntegrations??!0,Fe=new Set(m.debugDiagnosticTools??he),Ie=(0,d.createFablePlanBrokerClient)(()=>G?.sessionManager.getSessionId()),ze=m.fableBroker??{start:(e,t)=>Ie.start(e,t),cancel:(e,t)=>Ie.cancel({requester:d.FABLE_PLAN_REQUESTER,operationId:e,reason:t})},Be=()=>m.fableBroker!==void 0||Ie.isAvailable(),Ve=q?(0,f.registerMinorModeOwner)(e,{descriptor:{source:k,id:`plan`,label:`Plan`,description:`Read-only planning with normal, debug, and Fable flavors.`,order:40,actions:[{id:se,label:`Activate`,description:`Activate plan mode or switch its planning flavor.`,contexts:[`tui`,`headless`],parameters:[{name:`flavor`,label:`Flavor`,kind:`enum`,required:!0,choices:[{value:`normal`,label:`Normal`},{value:`debug`,label:`Debug`},{value:`fable`,label:`Fable`}]}]},{id:ce,label:`Deactivate`,description:`Exit plan mode and restore the previous agent configuration.`,contexts:[`tui`,`headless`],parameters:[]}]},initialState:{activation:`inactive`,condition:`ready`,actions:[{id:se,enabled:!0},{id:ce,enabled:!1,disabledReason:`Plan mode is inactive.`}]},async handleAction(e,t,n){if(e===se){let e=t.flavor;if(e!==`normal`&&e!==`debug`&&e!==`fable`)throw Error(`A valid plan flavor is required.`);return await Q(()=>$(n.context,e,I,!1)),{message:`Plan mode is active with the ${e} flavor.`}}if(e===ce)return{message:await Q(()=>st(n.context,I))?`Plan mode deactivated.`:`Plan mode remains active.`};throw Error(`Unknown plan mode action: ${e}`)},onError:e=>void c.recordError(r.PLAN_EVENT.configLoadFailed,e)}):{publish:()=>void 0},J=q?(0,_.createDoomLeaderContribution)(e,{source:k,bindings:et(!1)}):{update:()=>void 0},He,We=q?(0,g.registerDoomConfigContribution)(e,{source:k,listSections:()=>{try{return i.planConfigSections(t(),He)}catch(e){return i.planConfigSections(void 0,e instanceof Error?e.message:String(e))}},handlers:{[g.CONFIG_ACTION.set]:async({fieldId:e,value:t})=>{let n=i.planSettingByFieldId(e);!n||!t||(He=void 0,await(0,u.setDoomConfigValue)((0,o.globalDoomConfigPath)(),[...n.keyPath],t))},[g.CONFIG_ACTION.clear]:async({fieldId:e})=>{let t=i.planSettingByFieldId(e);t&&(He=void 0,await(0,u.unsetDoomConfigValue)((0,o.globalDoomConfigPath)(),[...t.keyPath]))}},onError:e=>{He=e instanceof Error?e.message:String(e)}}):{dispose:()=>void 0,update:()=>void 0};function Y(){J.update(et(S))}function X(e){Y();let t=w,n=S&&t?`plan:${t}`:void 0,r=t===`fable`&&U!==`idle`?` · ${U}`:``;e.ui.setStatus(`plan-mode`,n?e.ui.theme.fg(A,n):void 0);let i={activation:S?`active`:`inactive`,condition:U===`failed`?`failed`:U===`interrupted`?`degraded`:`ready`,...S&&t?{detail:`${t}${r} - read only`,color:A}:{},actions:[{id:se,enabled:!0},...S?[{id:ce,enabled:!0}]:[{id:ce,enabled:!1,disabledReason:`Plan mode is inactive.`}]]};Ve.publish(i)}function tt(){if(!q||!S||!w||!G)return;let t={owner:k,allowedTools:[...Se],requiredTools:[C,`mcp`],allowMcpTools:!0,allowedExternalProfiles:w===`fable`?[n.FABLE_PLAN_PROFILE]:[],denyExtensions:!1};O?O.update(t):O=(0,p.registerSubagentPolicy)((0,ne.createProtocolRuntime)({bus:e.events,source:k,sessionId:G.sessionManager.getSessionId()}),t)}function Z(){e.appendEntry(y,{version:2,...S&&w?{activeFlavor:w}:{},...T?{originalSnapshot:{tools:[...T.tools],...T.model?{model:{...T.model}}:{},thinking:T.thinking}}:{},...F?{planId:F}:{},...W?{interruptedFableStage:W}:{}})}function nt(e,t,n){c.recordWarning(r.PLAN_EVENT.modelResolveFailed,`Planning model ${n}: ${t}`,{[de]:t,"plan.model.phase":e,"plan.model.reason":n})}async function rt(t){let n=E?.main;if(n){if(n.model){let r=Qe(n.model,t);r?await e.setModel(r)||(t.ui.notify(`Planning model is unavailable without authentication: ${n.model}`,A),nt(`apply`,n.model,pe)):(t.ui.notify(`Planning model not found: ${n.model}`,A),nt(`apply`,n.model,fe))}n.thinking&&e.setThinkingLevel(n.thinking)}}async function it(t,n){if(!n)return!1;if(n.model){let i=`${n.model.provider}/${n.model.id}`,a=t.modelRegistry.find(n.model.provider,n.model.id);if(!a)return t.ui.notify(`Previous model not found: ${i}`,A),nt(`restore`,i,fe),!1;try{if(!await e.setModel(a))return t.ui.notify(`Previous model is unavailable without authentication: ${i}`,A),nt(`restore`,i,pe),!1}catch(e){return t.ui.notify(`Previous model could not be restored: ${i}`,A),nt(`restore`,i,me),c.recordError(r.PLAN_EVENT.modelResolveFailed,e,{[de]:i,"plan.model.phase":`restore`,"plan.model.reason":me}),!1}}return e.setThinkingLevel(n.thinking),!0}function at(e){S&&w?e.ui.notify(`Already in plan:${w}.`,le):e.ui.notify(`Plan mode is inactive.`,le)}function Q(e){let t=Ne.then(e,e);return Ne=t.then(()=>void 0,()=>void 0),t}async function ot(e){if(!K&&!U.match(/^(draft|review)$/u))return;(U===`draft`||U===`review`)&&(W=U),lt.cancel(e);let t=K;if(t)try{await t}catch(e){c.recordError(r.PLAN_EVENT.modeDisabled,e,{[M]:`fable`,"plan.fable.reason":`cancel_failed`})}K=void 0,W&&(U=`interrupted`),G&&X(G),Z()}async function $(n,i,a,o){if(G=n,S){if(w===i){at(n);return}w===`fable`&&await ot(`Leaving Fable for plan:${i}.`),w=i,tt(),e.setActiveTools(Ge(T?.tools??[],e.getActiveTools(),e.getAllTools().map(e=>e.name),i,Fe)),X(n),Z(),c.recordEvent(r.PLAN_EVENT.modeEnabled,{[j]:a,[M]:i,"plan.tool.count":e.getActiveTools().length});return}let s;try{s=t()}catch(e){throw c.recordError(r.PLAN_EVENT.configLoadFailed,e,{[j]:a}),e}o?F??=Ae():(P=void 0,L=!1,R=!1,F=Ae(),W=void 0,U=`idle`),E=s,T??={tools:[...e.getActiveTools()],...n.model?{model:{provider:n.model.provider,id:n.model.id}}:{},thinking:e.getThinkingLevel()},S=!0,w=i,e.setActiveTools(Ge(T.tools,e.getActiveTools(),e.getAllTools().map(e=>e.name),i,Fe)),tt(),await rt(n),X(n),Z(),c.recordEvent(r.PLAN_EVENT.modeEnabled,{[j]:a,[M]:i,"plan.tool.count":e.getActiveTools().length,...E?.main?.model?{[de]:E.main.model}:{},...E?.main?.thinking?{"plan.thinking":E.main.thinking}:{}})}async function st(t,n){if(!S)return at(t),!1;await ot(`Plan mode is exiting.`);let i=T;if(!await it(t,i))return t.ui.notify(`Previous model was not restored. Plan mode remains read-only.`,A),X(t),Z(),c.recordWarning(r.PLAN_EVENT.modeDisabled,`Plan mode restoration failed.`,{[j]:n,[M]:w??`unknown`,"plan.restored":!1}),!1;let a=!!P;return e.setActiveTools(Ke(i?.tools??[],e.getActiveTools(),e.getAllTools().map(e=>e.name))),O?.dispose(),O=void 0,S=!1,w=void 0,E=void 0,R=!1,T=void 0,B=void 0,U=`idle`,W=void 0,X(t),Z(),c.recordEvent(r.PLAN_EVENT.modeDisabled,{[j]:n,[M]:`normal`,"plan.written":a,"plan.restored":!0}),!0}let ct=[];if(q){let t=e,n=e=>{if(e.aborted)throw e.reason instanceof Error?e.reason:Error(`Plan voice transition was cancelled.`)},r={descriptor:{source:we,id:`plan-activate`,name:`activate_plan`,label:`Activate Plan`,description:`Activate or switch the serialized read-only planning mode flavor.`,order:10,inputSchema:Te,resultSchema:De},execute(e,t){let r=Pe(H(e)?e.flavor:void 0);if(!r)throw Error(`A valid plan flavor is required.`);return n(t.signal),Q(async()=>{n(t.signal);let e=S,i=w;return await $(t.context,r,Ce,!1),{active:S,flavor:w??r,changed:e!==S||i!==w}})}},i={descriptor:{source:we,id:`plan-exit`,name:`exit_plan`,label:`Exit Plan`,description:`Exit read-only planning mode and restore the previous agent configuration.`,order:20,inputSchema:Ee,resultSchema:De},execute(e,t){return n(t.signal),Q(async()=>{n(t.signal);let e=S,r=await st(t.context,Ce);return{active:S,flavor:w??null,changed:e!==S||r}})}};ct.push((0,h.registerVoiceToolContribution)(t,r)),ct.push((0,h.registerVoiceToolContribution)(t,i))}let lt=n.createFablePlanFlow({broker:ze,isAuthorized:()=>S&&w===`fable`&&Be(),onStage:e=>{U=e,(e===`completed`||e===`failed`||e===`cancelled`)&&(W=void 0),G&&X(G),S&&Z()},onError:e=>{c.recordError(r.PLAN_EVENT.modeEnabled,e,{[M]:`fable`,"plan.fable.reason":`flow_error`})}});e.registerTool({name:oe,label:`Record Debug Evidence`,description:`Record optional bounded debug evidence while planning a repository fix.`,promptSnippet:`Record the issue and any relevant reproduction, logs, traces, process output, or browser evidence`,parameters:{type:`object`,properties:{issue:{type:`string`},expectedBehavior:{type:`string`},reproductionAttempt:{type:`string`},actualBehavior:{type:`string`},logs:{type:`array`,items:{type:`string`}},correlatedTraceEvidence:{type:`array`,items:{type:`string`}},processOutput:{type:`array`,items:{type:`string`}},browserConsoleEvidence:{type:`array`,items:{type:`string`}},correlationIds:{type:`array`,items:{type:`string`}},timestamps:{type:`array`,items:{type:`string`}},verifiedFacts:{type:`array`,items:{type:`string`}},hypotheses:{type:`array`,items:{type:`string`}},unavailableEvidence:{type:`array`,items:{type:`string`}}},required:[`issue`],additionalProperties:!1},async execute(e,t){if(!S||w!==`debug`)return{content:[{type:`text`,text:`Debug planning is not active.`}],details:{recorded:!1}};try{B=Ue(t)}catch(e){throw c.recordWarning(r.PLAN_EVENT.modeEnabled,e,{[M]:`debug`,"plan.debug.reason":`invalid_evidence`}),e}return G&&X(G),{content:[{type:`text`,text:`Debug evidence recorded as optional planning context.`}],details:{recorded:!0}}}}),e.registerTool({name:D,label:`Run Fable Plan`,description:`Send a bounded, sanitized planning packet to the local Fable broker for one repository-aware draft.`,promptSnippet:`Run the local Fable draft with the bounded planning packet`,parameters:{type:`object`,properties:{goal:{type:`array`,items:{type:`string`}},constraints:{type:`array`,items:{type:`string`}},decisions:{type:`array`,items:{type:`string`}},verifiedFindings:{type:`array`,items:{type:`object`}},inferredFindings:{type:`array`,items:{type:`string`}},unresolvedQuestions:{type:`array`,items:{type:`string`}},currentPlan:{type:`string`}},additionalProperties:!1},async execute(e,t,n){if(!S||w!==`fable`)return{content:[{type:`text`,text:`Fable planning is not active.`}],details:{started:!1}};if(!Be())return{content:[{type:`text`,text:`The local Fable broker is unavailable. Fable planning remains disabled.`}],details:{started:!1,errorCode:`broker_unavailable`}};let r=lt.run(t,n);K=r;try{let e=await r;return{content:[{type:`text`,text:e.draft?`Fable draft:\n${e.draft}`:`Fable planning ${e.status}: ${e.errorCode??`no output`}.`}],details:{...e,started:!0}}}finally{K===r&&(K=void 0)}}}),e.registerTool({name:x,label:`Write Plan`,description:`After presenting the complete implementation plan as Markdown in chat, save that visible plan to a unique Markdown file in the configured plans directory.`,promptSnippet:`Save the implementation plan already presented in chat to the configured plans directory`,parameters:{type:`object`,properties:{},additionalProperties:!1},async execute(t,n,i,a,u){if(!S)return{content:[{type:`text`,text:`Plan mode is disabled. Use normal file tools instead.`}],details:{written:!1}};let d=je(u.sessionManager.getBranch(),t);if(!d){let e=Error(`Present the complete implementation plan as visible Markdown in chat before calling write_plan.`);throw c.recordError(r.PLAN_EVENT.writePlanFailed,e,{"plan.reason":`missing_visible_plan`}),e}let f=Date.now(),ne=(0,o.getHarnessState)().root??u.cwd,p=(0,o.resolvePlanningPlansDirectory)(E?.plansDirectory,ne,ee.default.homedir()),m=ke(u.sessionManager.getSessionId());F??=Ae();let h=P?.planId===F&&te.default.dirname(P.path)===p?P.path:void 0,g=Oe(d),_=F,v=h??te.default.join(p,`${g}--${_}.md`),y=new AbortController,b=Error(`Writing ${v} timed out after ${ge}ms.`),x=setTimeout(()=>y.abort(b),ge),C=i?AbortSignal.any([i,y.signal]):y.signal,w=`checking`,T=()=>{a?.({content:[{type:`text`,text:`${w===`checking`?`Checking`:`Writing`} ${v}...`}],details:{phase:w,path:v,startedAt:f}})},ie=(e,t)=>{c.recordWarning(r.PLAN_EVENT.writePlanUnsafePath,t,{"plan.phase":w,"plan.refusal":e})};try{T();try{await V(()=>l.default.promises.mkdir(p,{recursive:!0,mode:448}),C)}catch(e){throw C.aborted?Me(C):Error(`Could not create the configured plans directory ${p}.`,{cause:e})}let t=await V(()=>l.default.promises.lstat(p),C),n=await V(()=>l.default.promises.realpath(p),C);if(t.isSymbolicLink()||!t.isDirectory())return ie(`unsafe_plans_directory`,`Refused to write the plan because the configured path is unsafe.`),{content:[{type:`text`,text:`Refused to write the plan because the configured path is unsafe.`}],details:{written:!1,path:v,phase:w,durationMs:Date.now()-f}};w=`writing`,T();let i;try{for(let e=0;e<3;e+=1)try{let e=h?0:l.default.constants.O_EXCL;i=await V(()=>l.default.promises.open(v,l.default.constants.O_CREAT|l.default.constants.O_WRONLY|l.default.constants.O_NONBLOCK|l.default.constants.O_NOFOLLOW|e,384),C);break}catch(t){if(!(!h&&t instanceof Error&&`code`in t&&String(t.code)===`EEXIST`)||e===2)throw t;_=Ae(),F=_,v=te.default.join(p,`${g}--${_}.md`),Z()}if(!i)throw Error(`Could not allocate a unique plan filename in ${p}.`);let e=await V(()=>l.default.promises.realpath(p),C),t=await V(()=>i.stat(),C);if(e!==n||!t.isFile()||t.nlink!==1)return ie(`invalid_destination`,ue),{content:[{type:`text`,text:ue}],details:{written:!1,path:v,phase:w,durationMs:Date.now()-f}};await V(()=>i.truncate(0),C),await V(()=>i.writeFile(d,{encoding:`utf8`,signal:C}),C)}catch(e){if(e instanceof Error&&`code`in e&&[`EISDIR`,`ELOOP`,`ENXIO`].includes(String(e.code)))return ie(`invalid_destination`,ue),{content:[{type:`text`,text:ue}],details:{written:!1,path:v,phase:w,durationMs:Date.now()-f}};throw e}finally{await i?.close()}return P={content:d,path:v,sessionId:m,planId:_,title:g,writtenAt:new Date().toISOString()},e.appendEntry(re,P),L=!0,R=!1,c.recordEvent(r.PLAN_EVENT.planWritten,{"plan.written":!0,"plan.bytes":s.Buffer.byteLength(d,`utf8`),"plan.duration_ms":Date.now()-f,"plan.revised":!!h}),{content:[{type:`text`,text:`Wrote implementation plan to ${v}.`}],details:{written:!0,path:v,phase:w,durationMs:Date.now()-f}}}catch(e){let t={"plan.phase":w,"plan.duration_ms":Date.now()-f};if(y.signal.aborted&&!i?.aborted){let n=Error(`write_plan timed out during ${w} for ${v}.`,{cause:e});throw c.recordError(r.PLAN_EVENT.writePlanTimedOut,n,{...t,"plan.timeout_ms":ge}),n}throw c.recordError(r.PLAN_EVENT.writePlanFailed,e,{...t,"plan.cancelled":i?.aborted??!1}),e}finally{clearTimeout(x)}}});async function ut(e,t){if(c.recordEvent(r.PLAN_EVENT.planReviewCompleted,{"plan.outcome":e===N?`exited`:`continued`}),e===N){let e=await Q(()=>st(t,`plan_approved`));return{content:[{type:`text`,text:e?`The user approved exiting plan mode. Full tool access is restored. Begin implementing the approved plan.`:`The previous model could not be restored. Plan mode remains read-only.`}],details:{exited:e}}}return L=!1,{content:[{type:`text`,text:`The user chose to continue planning. Remain read-only and refine the plan.`}],details:{exited:!1}}}e.registerTool({name:b,label:`Complete Plan`,description:`Present the saved implementation plan for exit-or-continue approval. Interactive sessions use the normal selector; autonomous voice narrates a plain-text handoff and waits for the next user message.`,promptSnippet:`Request explicit exit-or-continue approval after the saved plan has been presented`,promptGuidelines:[`After write_plan succeeds, call complete_plan without a decision so it can present the review question.`,`When autonomous voice returns an awaiting-response result, stop. Interpret the next ordinary user message, then call complete_plan again with decision "exit" or "continue".`,`Never pass decision "${N}" without the user explicitly choosing "${_e}".`],parameters:{type:`object`,properties:{decision:{type:`string`,enum:[N,ye]}},additionalProperties:!1},async execute(e,t,n,i,a){if(!S)return{content:[{type:`text`,text:`Plan mode is already disabled.`}],details:{exited:!1}};if(!L)return{content:[{type:`text`,text:`Present the complete plan in chat and save it with write_plan before requesting approval.`}],details:{exited:!1}};if(!a.hasUI)return c.recordEvent(r.PLAN_EVENT.planReviewCompleted,{"plan.outcome":`no_ui`}),{content:[{type:`text`,text:`The plan is complete, but this run cannot ask the user interactively. Remain in plan mode until the user uses SPC p e.`}],details:{exited:!1}};let o=H(t)?t.decision:void 0,s=o===N||o===ye;if(R){if(!s)throw Error(`The narrated plan review is waiting for an explicit exit or continue decision.`);return R=!1,ut(o,a)}if(o!==void 0)throw Error(`Call complete_plan without a decision before submitting a narrated plan-review answer.`);let l=z?.handoff(be);return l?(R=!0,(0,v.buildVoiceToolResult)(l)):ut(await a.ui.select(`Plan complete. What would you like to do?`,[_e,ve])===_e?N:ye,a)}}),q&&(0,_.registerDoomLeaderActionHandlers)(e,{source:k,handlers:{"plan.normal":()=>{let e=G;return e?Q(()=>$(e,`normal`,I,!1)):void 0},"plan.exit":()=>{let e=G;return e?Q(async()=>{await st(e,I)}):void 0},"plan.debug":()=>{let e=G;return e?Q(()=>$(e,`debug`,I,!1)):void 0},"plan.fable":()=>{let e=G;return e?Q(()=>$(e,`fable`,I,!1)):void 0}},onError:(e,t)=>{G?.hasUI&&G.ui.notify(`Leader action ${t} failed. Plan mode remains read-only.`,A),c.recordError(r.PLAN_EVENT.modeEnabled,e,{[j]:I,"plan.action":t})}}),e.on(`tool_call`,async(e,t)=>{if(!S)return;let n=w===`debug`&&(e.toolName===oe||Fe.has(e.toolName))||w===`fable`&&e.toolName===D;if(!xe.has(e.toolName)&&!n)return{block:!0,reason:`Plan mode blocks the ${e.toolName} tool. Use SPC p e to restore access.`};let r=Je(E?.subagents,t.model);if(e.toolName===ae){r&&Xe(e.input,r);return}if(e.toolName!==ie)return;let i=e.input;if(Ze(i.action))return{block:!0,reason:`Plan mode blocks subagent management action '${i.action}'. Use SPC p e first.`};qe(i),r&&Ye(i,r)}),e.on(`before_agent_start`,async(e,t)=>{let n=[];if(S){let e=(0,o.getHarnessState)().root??t.cwd,r=(0,o.resolvePlanningPlansDirectory)(E?.plansDirectory,e,ee.default.homedir());n.push(`[PLAN MODE ACTIVE]\nYou are in repository read-only plan mode. The dedicated write_plan tool may write one unique Markdown plan file under ${r}.\n\nExplore the codebase and produce a concrete implementation plan. For every plan, first call subagent with action "agents", cluster the exploration by independent domain, subsystem, or integration boundary, and create a provisional task graph with the task tool. Select specialized agents by matching their names and descriptions to each cluster. Assign every unblocked delegated task through the task tool, and use a one-shot inlineAgent with a focused systemPrompt when no discovered specialist fits. Treat the initial graph as provisional, not as a fixed contract. After findings arrive, review the entire graph at least once and perform one to three review passes in total. In each pass, use the evidence to add, rewrite, delete, cancel, reassign, or change blockedBy relationships for tasks when warranted. Do not keep following tasks that new information has made stale. Stop revising early when the graph is stable, or after the third pass.\n\nEvery plan must end with a delegated planning-draft stage blocked by all exploration and decision tasks. A single-boundary plan gets one planning draft. A complex plan spanning multiple subsystems, domains, packages, apps, or integration boundaries gets two planning drafts concurrently. Use three concurrent drafts instead when the work is cross-layer, migration-sensitive, security-sensitive, or similarly high risk. Assign each draft through the task tool to the discovered "planner" agent with context "fork" so it receives the conversation and gathered evidence. If the planner agent is unavailable, assign the same draft task through the task tool with a focused inlineAgent. All children receive read, Bash, grep, find, ls, and configured MCP tools with artifacts disabled. Bash and MCP tools are for read-only inspection and must not modify files, external systems, or repository state. Doom Team runs asynchronously, so do not poll. After launch, continue non-overlapping exploration or end your turn; completion notifications wake the parent session.\n\nAfter all planning drafts complete, the main agent must compare the candidates, pick the strongest draft, cross-check it against the gathered evidence and the other drafts, resolve conflicts and gaps, and ask the user only for product decisions. A child produces the draft, but the main agent owns and synthesizes the final plan. Do not modify files or repository state except through write_plan. Start the final plan with a meaningful Markdown H1 because write_plan derives the filename from it. Present the complete plan as visible Markdown in chat, then call write_plan with no arguments. After write_plan succeeds, clear the completed durable task graph and call complete_plan without a decision. In an interactive text session, complete_plan uses the normal exit-or-continue selector. Under autonomous voice, it displays and narrates the choices without opening a blocking dialog, then ends the turn. Interpret the user's next ordinary message and call complete_plan again with decision "exit" or "continue". Do not exit plan mode without explicit approval.`,a.buildFlavorPlanningPrompt(w,r,B,U))}if(P&&n.push(`[CURRENT PLAN]\nSource: ${P.path}\n\n${P.content}`),n.length!==0)return{systemPrompt:`${e.systemPrompt}\n\n${n.join(`
|
|
4
|
+
|
|
5
|
+
`)}`}}),e.on(`context`,async e=>({messages:e.messages.filter(e=>e.customType!==`agent-harness-plan-mode-context`)})),e.on(`session_start`,async(t,n)=>{let r=n.sessionManager.getEntries(),i=r.flatMap(e=>e.type===`custom`&&e.customType===y?[Le(e.data)]:[]).filter(e=>e!==void 0).at(-1),a=n.sessionManager.getSessionId(),o=ke(a);z?.dispose(),z=q?(0,v.createVoiceQuestionHandoff)({bus:e.events,source:k,sessionId:a}):void 0;let s=r.flatMap(e=>e.type===`custom`&&e.customType===re?[Re(e.data)]:[]).filter(e=>e!==void 0).at(-1),c=T;if(O?.dispose(),O=void 0,P=s?.sessionId===o?s:void 0,F=i?.planId??P?.planId,L=!1,R=!1,E=void 0,B=void 0,S=!1,w=void 0,Y(),T=i?.originalSnapshot,W=i?.interruptedFableStage,U=W?`interrupted`:`idle`,G=n,i?.activeFlavor)await $(n,i.activeFlavor,`session_restore`,!0);else{let t=i?.originalSnapshot??c;t?await it(n,t)&&e.setActiveTools(Ke(t.tools,e.getActiveTools(),e.getAllTools().map(e=>e.name))):e.setActiveTools(e.getActiveTools().filter(e=>e!==b&&e!==x&&e!==oe&&e!==D)),T=void 0,X(n)}}),e.on(`session_shutdown`,async(t,n)=>{await ot(`Plan host session is shutting down.`),S&&T&&await it(n,T)&&e.setActiveTools(Ke(T.tools,e.getActiveTools(),e.getAllTools().map(e=>e.name))),O?.dispose(),O=void 0,z?.dispose(),z=void 0,R=!1,We.dispose();for(let e of ct)e.dispose();G=void 0,await c.shutdown()})}exports.WRITE_PLAN_TIMEOUT_MS=ge,exports.configurePlanningSubagentInput=Ye,exports.configurePlanningTaskInput=Xe,exports.constrainSubagentInput=qe,exports.createPlanIdentifier=Ae,exports.isBlockedSubagentManagementAction=Ze,exports.loadPlanningModeConfig=$e,exports.parseDebugEvidencePacket=Ue,exports.parsePersistedPlanState=Le,exports.planModeExtension=X,exports.planModeTools=We,exports.planSessionIdentifier=ke,exports.planTitleSlug=Oe,exports.planningSubagentModel=Je,exports.visiblePlanForToolCall=je;
|
|
6
|
+
//# sourceMappingURL=planMode.cjs.map
|