@astralyn/pi 0.82.4 → 0.82.6
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/CHANGELOG.md +52 -0
- package/dist/cli/project-trust.d.ts.map +1 -1
- package/dist/cli/project-trust.js +4 -1
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +2 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +4 -22
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/extensions/index.d.ts +2 -2
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +2 -3
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +37 -5
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +11 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +3 -13
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +6 -36
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/extensions/plan/constants.d.ts +11 -2
- package/dist/extensions/plan/constants.d.ts.map +1 -1
- package/dist/extensions/plan/constants.js +14 -2
- package/dist/extensions/plan/constants.js.map +1 -1
- package/dist/extensions/plan/index.d.ts +0 -18
- package/dist/extensions/plan/index.d.ts.map +1 -1
- package/dist/extensions/plan/index.js +35 -3
- package/dist/extensions/plan/index.js.map +1 -1
- package/dist/extensions/plan/view.d.ts +36 -0
- package/dist/extensions/plan/view.d.ts.map +1 -0
- package/dist/extensions/plan/view.js +74 -0
- package/dist/extensions/plan/view.js.map +1 -0
- package/dist/extensions/question/dialog.d.ts +3 -1
- package/dist/extensions/question/dialog.d.ts.map +1 -1
- package/dist/extensions/question/dialog.js +106 -52
- package/dist/extensions/question/dialog.js.map +1 -1
- package/dist/extensions/question/index.d.ts.map +1 -1
- package/dist/extensions/question/index.js +2 -2
- package/dist/extensions/question/index.js.map +1 -1
- package/dist/extensions/question/render-cache.d.ts +9 -0
- package/dist/extensions/question/render-cache.d.ts.map +1 -1
- package/dist/extensions/question/render-cache.js +22 -0
- package/dist/extensions/question/render-cache.js.map +1 -1
- package/dist/extensions/question/results.d.ts.map +1 -1
- package/dist/extensions/question/results.js +6 -1
- package/dist/extensions/question/results.js.map +1 -1
- package/dist/extensions/question/schema.d.ts +4 -0
- package/dist/extensions/question/schema.d.ts.map +1 -1
- package/dist/extensions/question/schema.js +19 -28
- package/dist/extensions/question/schema.js.map +1 -1
- package/dist/extensions/question/types.d.ts +1 -1
- package/dist/extensions/question/types.d.ts.map +1 -1
- package/dist/extensions/question/types.js.map +1 -1
- package/dist/extensions/router/stream.d.ts.map +1 -1
- package/dist/extensions/router/stream.js +44 -0
- package/dist/extensions/router/stream.js.map +1 -1
- package/dist/extensions/subagent/activity.d.ts.map +1 -1
- package/dist/extensions/subagent/activity.js +25 -4
- package/dist/extensions/subagent/activity.js.map +1 -1
- package/dist/extensions/subagent/agents.d.ts.map +1 -1
- package/dist/extensions/subagent/agents.js +12 -6
- package/dist/extensions/subagent/agents.js.map +1 -1
- package/dist/extensions/subagent/constants.d.ts +1 -1
- package/dist/extensions/subagent/constants.d.ts.map +1 -1
- package/dist/extensions/subagent/constants.js +3 -2
- package/dist/extensions/subagent/constants.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +14 -0
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/subagent/render.d.ts.map +1 -1
- package/dist/extensions/subagent/render.js +243 -116
- package/dist/extensions/subagent/render.js.map +1 -1
- package/dist/extensions/subagent/resolve.d.ts.map +1 -1
- package/dist/extensions/subagent/resolve.js +13 -9
- package/dist/extensions/subagent/resolve.js.map +1 -1
- package/dist/extensions/subagent/runner.d.ts +1 -1
- package/dist/extensions/subagent/runner.d.ts.map +1 -1
- package/dist/extensions/subagent/runner.js +9 -3
- package/dist/extensions/subagent/runner.js.map +1 -1
- package/dist/extensions/subagent/schema.d.ts.map +1 -1
- package/dist/extensions/subagent/schema.js +4 -4
- package/dist/extensions/subagent/schema.js.map +1 -1
- package/dist/extensions/subagent/sdk-runner.d.ts.map +1 -1
- package/dist/extensions/subagent/sdk-runner.js +5 -0
- package/dist/extensions/subagent/sdk-runner.js.map +1 -1
- package/dist/extensions/subagent/types.d.ts +7 -0
- package/dist/extensions/subagent/types.d.ts.map +1 -1
- package/dist/extensions/subagent/types.js.map +1 -1
- package/dist/extensions/todo/constants.d.ts +17 -6
- package/dist/extensions/todo/constants.d.ts.map +1 -1
- package/dist/extensions/todo/constants.js +47 -9
- package/dist/extensions/todo/constants.js.map +1 -1
- package/dist/extensions/todo/index.d.ts +1 -15
- package/dist/extensions/todo/index.d.ts.map +1 -1
- package/dist/extensions/todo/index.js +35 -4
- package/dist/extensions/todo/index.js.map +1 -1
- package/dist/extensions/todo/schema.d.ts +59 -7
- package/dist/extensions/todo/schema.d.ts.map +1 -1
- package/dist/extensions/todo/schema.js +72 -12
- package/dist/extensions/todo/schema.js.map +1 -1
- package/dist/extensions/todo/state.d.ts +20 -5
- package/dist/extensions/todo/state.d.ts.map +1 -1
- package/dist/extensions/todo/state.js +1016 -134
- package/dist/extensions/todo/state.js.map +1 -1
- package/dist/extensions/todo/view.d.ts +16 -1
- package/dist/extensions/todo/view.d.ts.map +1 -1
- package/dist/extensions/todo/view.js +293 -7
- package/dist/extensions/todo/view.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +6 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +14 -6
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +6 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +41 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +8 -1
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/utils/coalescing-terminal.d.ts +71 -17
- package/dist/utils/coalescing-terminal.d.ts.map +1 -1
- package/dist/utils/coalescing-terminal.js +136 -31
- package/dist/utils/coalescing-terminal.js.map +1 -1
- package/docs/bundled/extensions/plan.md +6 -4
- package/docs/bundled/extensions/question.md +9 -7
- package/docs/bundled/extensions/subagent.md +4 -4
- package/docs/bundled/extensions/todo.md +9 -5
- package/docs/bundled/tool-presentation.md +1 -1
- package/docs/extensions.md +14 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/utils/output-decoder.d.ts +0 -52
- package/dist/utils/output-decoder.d.ts.map +0 -1
- package/dist/utils/output-decoder.js +0 -134
- package/dist/utils/output-decoder.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../src/extensions/question/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"schema.js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U,GAAG,IAAI,GAAG,EAAU,CAAC;QACrC,KAAK,MAAM,MAAM,IAAI,CAAC,CAAC,OAA2B,EAAE,CAAC;YACpD,MAAM,QAAQ,GAAG,cAAc,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC9C,IAAI,mBAAmB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACvC,OAAO;oBACN,EAAE,EAAE,KAAK;oBACT,KAAK,EAAE,gBAAgB;oBACvB,OAAO,EAAE,6BAA6B,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;iBACnE,CAAC;YACH,CAAC;YACD,IAAI,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAC9B,OAAO;oBACN,EAAE,EAAE,KAAK;oBACT,KAAK,EAAE,wBAAwB;oBAC/B,OAAO,EAAE,gDAAgD;iBACzD,CAAC;YACH,CAAC;YACD,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC1B,CAAC;IACF,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;AAAA,CACpB","sourcesContent":["import { Type } from \"typebox\";\nimport { QUESTION_LIMITS } from \"./limits.ts\";\nimport type { Question, QuestionOption, QuestionToolError } from \"./types.ts\";\n\nconst MIN_OPTIONS = 2;\nconst MAX_OPTIONS = 4;\nconst MAX_QUESTIONS = 4;\nconst RESERVED_LABELS = [\"Other\", \"Type something.\", \"Chat about this\"] as const;\n\nconst normalizeLabel = (text: string) => text.trim().toLowerCase();\nconst RESERVED_NORMALIZED = new Set(RESERVED_LABELS.map(normalizeLabel));\n\nconst OptionSchema = Type.Object({\n\tlabel: Type.String({\n\t\tmaxLength: QUESTION_LIMITS.optionLabelChars,\n\t\tdescription:\n\t\t\t\"Short user-facing option label (1-5 words), distinct within the question. Reserved labels ('Other', 'Type something.', 'Chat about this') are rejected — the UI adds the custom-answer path itself.\",\n\t}),\n\tdescription: Type.String({\n\t\tmaxLength: QUESTION_LIMITS.optionDescriptionChars,\n\t\tdescription: \"One concise sentence explaining the option's meaning, consequence, or tradeoff.\",\n\t}),\n\tpreview: Type.Optional(\n\t\tType.String({\n\t\t\tmaxLength: QUESTION_LIMITS.previewChars,\n\t\t\tdescription:\n\t\t\t\t\"Optional markdown preview shown only for focused single-select options; use for concrete snippets, layouts, copy, or config comparisons.\",\n\t\t}),\n\t),\n});\n\nconst QuestionSchema = Type.Object({\n\tquestion: Type.String({\n\t\tmaxLength: QUESTION_LIMITS.questionChars,\n\t\tdescription:\n\t\t\t\"One clear, specific decision or preference question ending in a question mark. Ask only what is needed to proceed.\",\n\t}),\n\theader: Type.String({\n\t\tmaxLength: QUESTION_LIMITS.headerChars,\n\t\tdescription: \"Very short decision label shown as a chip; aim for ~12 chars, max 32. E.g. 'Auth method'.\",\n\t}),\n\toptions: Type.Array(OptionSchema, {\n\t\tminItems: MIN_OPTIONS,\n\t\tmaxItems: MAX_OPTIONS,\n\t\tdescription: \"Mutually distinct options for this decision; do not include reserved custom-answer labels.\",\n\t}),\n\tmultiSelect: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"Allow selecting multiple options only when choices can be combined. Defaults to false for mutually exclusive decisions.\",\n\t\t}),\n\t),\n});\n\nexport const QuestionParams = Type.Object({\n\tquestions: Type.Array(QuestionSchema, {\n\t\tminItems: 1,\n\t\tmaxItems: MAX_QUESTIONS,\n\t\tdescription: \"Related decisions to ask now (1-4); ask only what is needed to unblock progress.\",\n\t}),\n});\n\n/**\n * Checks the schema cannot express. Length and count limits are omitted:\n * the agent core validates params against `QuestionParams` before execute runs.\n */\nexport function validateQuestions(\n\tquestions: Question[],\n): { ok: true } | { ok: false; error: QuestionToolError; message: string } {\n\tconst seenQuestions = new Set<string>();\n\tfor (const q of questions) {\n\t\tconst questionKey = normalizeLabel(q.question);\n\t\tif (seenQuestions.has(questionKey)) {\n\t\t\treturn { ok: false, error: \"duplicate_question\", message: \"Question text must be unique\" };\n\t\t}\n\t\tseenQuestions.add(questionKey);\n\n\t\tif (q.multiSelect && q.options.some((option) => option.preview)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: \"preview_multiselect\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"Option previews are not supported on multiSelect questions; drop the previews or make the question single-select\",\n\t\t\t};\n\t\t}\n\n\t\tconst seenLabels = new Set<string>();\n\t\tfor (const option of q.options as QuestionOption[]) {\n\t\t\tconst labelKey = normalizeLabel(option.label);\n\t\t\tif (RESERVED_NORMALIZED.has(labelKey)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: \"reserved_label\",\n\t\t\t\t\tmessage: `Option label is reserved (${RESERVED_LABELS.join(\", \")})`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (seenLabels.has(labelKey)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: \"duplicate_option_label\",\n\t\t\t\t\tmessage: \"Option labels must be unique within a question\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tseenLabels.add(labelKey);\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n"]}
|
|
@@ -10,7 +10,7 @@ export interface Question {
|
|
|
10
10
|
multiSelect?: boolean;
|
|
11
11
|
}
|
|
12
12
|
export type InputMode = "custom" | "notes" | undefined;
|
|
13
|
-
export type QuestionToolError = "no_ui" | "
|
|
13
|
+
export type QuestionToolError = "no_ui" | "duplicate_question" | "duplicate_option_label" | "reserved_label" | "preview_multiselect";
|
|
14
14
|
export interface AnswerNote {
|
|
15
15
|
option: string;
|
|
16
16
|
text: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/extensions/question/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;A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AM,CAAC;CACjB;AAED,MAAM,MAAM,eAAe,GAAG,UAAU,GAAG,WAAW,GAAG,qBAAqB,GAAG,OAAO,CAAC;AAEzF,MAAM,WAAW,mBAAmB;IACnC,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,OAAO,EAAE,eAAe,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC1B;AAED,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,cAAc,CAAC;IAC9B,aAAa,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC3B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IAC5B,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,OAAO,EAAE,eAAe,CAAC;CACzB;AAED,MAAM,MAAM,aAAa,GACtB,CAAC,cAAc,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,GAC1D;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,IAAI,CAAA;CAAE,CAAC;AAEnD,eAAO,MAAM,YAAY,EAAE,aAA0E,CAAC","sourcesContent":["export interface QuestionOption {\n\tlabel: string;\n\tdescription: string;\n\tpreview?: string;\n}\n\nexport interface Question {\n\tquestion: string;\n\theader: string;\n\toptions: QuestionOption[];\n\tmultiSelect?: boolean;\n}\n\nexport type InputMode = \"custom\" | \"notes\" | undefined;\n\nexport type QuestionToolError =\n\t| \"no_ui\"\n\t| \"duplicate_question\"\n\t| \"duplicate_option_label\"\n\t| \"reserved_label\"\n\t| \"preview_multiselect\";\n\nexport interface AnswerNote {\n\toption: string;\n\ttext: string;\n}\n\nexport interface QuestionAnswer {\n\tquestionIndex: number;\n\tquestion: string;\n\theader: string;\n\tkind: \"option\" | \"custom\" | \"multi\";\n\tanswer: string | null;\n\tselected?: string[];\n\tnotes?: AnswerNote[];\n\tpreview?: string;\n}\n\nexport type QuestionOutcome = \"answered\" | \"cancelled\" | \"needs_clarification\" | \"error\";\n\nexport interface QuestionToolDetails {\n\tanswers: QuestionAnswer[];\n\toutcome: QuestionOutcome;\n\tcancelled: boolean;\n\terror?: QuestionToolError;\n}\n\nexport interface CustomAnswer {\n\ttext: string;\n\tselected: boolean;\n}\n\nexport interface QuestionState {\n\toptionIndex: number;\n\tsingleAnswer?: QuestionAnswer;\n\tmultiSelected: Set<number>;\n\tcustomAnswer?: CustomAnswer;\n\tnotesByOption: Map<string, string>;\n\twarning?: string;\n}\n\nexport interface DialogResult {\n\tanswers: QuestionAnswer[];\n\toutcome: QuestionOutcome;\n}\n\nexport type DisplayOption =\n\t| (QuestionOption & { kind: \"option\"; optionIndex: number })\n\t| { kind: \"other\"; label: string; isOther: true };\n\nexport const OTHER_OPTION: DisplayOption = { kind: \"other\", label: \"Type something.\", isOther: true };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/extensions/question/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/extensions/question/types.ts"],"names":[],"mappings":"AAsEA,MAAM,CAAC,MAAM,YAAY,GAAkB,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC","sourcesContent":["export interface QuestionOption {\n\tlabel: string;\n\tdescription: string;\n\tpreview?: string;\n}\n\nexport interface Question {\n\tquestion: string;\n\theader: string;\n\toptions: QuestionOption[];\n\tmultiSelect?: boolean;\n}\n\nexport type InputMode = \"custom\" | \"notes\" | undefined;\n\nexport type QuestionToolError =\n\t| \"no_ui\"\n\t| \"duplicate_question\"\n\t| \"duplicate_option_label\"\n\t| \"reserved_label\"\n\t| \"preview_multiselect\";\n\nexport interface AnswerNote {\n\toption: string;\n\ttext: string;\n}\n\nexport interface QuestionAnswer {\n\tquestionIndex: number;\n\tquestion: string;\n\theader: string;\n\tkind: \"option\" | \"custom\" | \"multi\";\n\tanswer: string | null;\n\tselected?: string[];\n\tnotes?: AnswerNote[];\n\tpreview?: string;\n}\n\nexport type QuestionOutcome = \"answered\" | \"cancelled\" | \"needs_clarification\" | \"error\";\n\nexport interface QuestionToolDetails {\n\tanswers: QuestionAnswer[];\n\toutcome: QuestionOutcome;\n\tcancelled: boolean;\n\terror?: QuestionToolError;\n}\n\nexport interface CustomAnswer {\n\ttext: string;\n\tselected: boolean;\n}\n\nexport interface QuestionState {\n\toptionIndex: number;\n\tsingleAnswer?: QuestionAnswer;\n\tmultiSelected: Set<number>;\n\tcustomAnswer?: CustomAnswer;\n\tnotesByOption: Map<string, string>;\n\twarning?: string;\n}\n\nexport interface DialogResult {\n\tanswers: QuestionAnswer[];\n\toutcome: QuestionOutcome;\n}\n\nexport type DisplayOption =\n\t| (QuestionOption & { kind: \"option\"; optionIndex: number })\n\t| { kind: \"other\"; label: string; isOther: true };\n\nexport const OTHER_OPTION: DisplayOption = { kind: \"other\", label: \"Type something.\", isOther: true };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../src/extensions/router/stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACN,KAAK,GAAG,EACR,KAAK,OAAO,EACZ,iCAAiC,EACjC,KAAK,KAAK,EAEV,KAAK,mBAAmB,EACxB,MAAM,8BAA8B,CAAC;AAMtC,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,UAAU,CAAC,OAAO,iCAAiC,CAAC,CA0EtD;AA4HD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAK3D;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAEhD","sourcesContent":["/**\n * Codex-oriented Responses client for API relays.\n *\n * Follows Pi's documented custom-provider pattern (see coding-agent docs\n * providers.md / custom-provider.md and examples/custom-provider-gitlab-duo):\n * wrap a built-in pi-ai stream API from `@earendil-works/pi-ai/compat` instead of\n * reimplementing SSE or deep-importing internal modules.\n *\n * We use openAIResponsesApi (works with relay sk- keys) and reshape the request\n * payload toward Codex CLI style so transparent gateways receive a friendlier body.\n */\n\nimport {\n\ttype Api,\n\ttype Context,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\topenAIResponsesApi,\n\ttype SimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\n\nimport { DEFAULTS, formatError, ROUTER_API } from \"./constants.ts\";\n\nconst responsesApi = openAIResponsesApi();\n\nexport function streamRouterCodex(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): ReturnType<typeof createAssistantMessageEventStream> {\n\tconst stream = createAssistantMessageEventStream();\n\n\tvoid (async () => {\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);\n\n\t\t\t// Built-in Responses stream expects api \"openai-responses\" on the model object.\n\t\t\tconst requestModel = {\n\t\t\t\t...model,\n\t\t\t\tapi: \"openai-responses\" as const,\n\t\t\t\tcompat: {\n\t\t\t\t\tsupportsDeveloperRole: true,\n\t\t\t\t\t// Avoid underscore session_id header that strict proxies reject.\n\t\t\t\t\tsessionAffinityFormat: \"openai-nosession\" as const,\n\t\t\t\t\t// Codex-style upstreams reject prompt_cache_retention: \"24h\".\n\t\t\t\t\tsupportsLongCacheRetention: false,\n\t\t\t\t\t...(model.compat ?? {}),\n\t\t\t\t},\n\t\t\t} as Model<\"openai-responses\">;\n\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\toriginator: DEFAULTS.originator,\n\t\t\t\t...(options?.headers as Record<string, string> | undefined),\n\t\t\t};\n\n\t\t\t// Prefer hyphenated Codex-style session affinity when we have a session id.\n\t\t\tconst sessionId = clampCacheKey(options?.sessionId);\n\t\t\tif (sessionId) {\n\t\t\t\tif (!headers[\"session-id\"]) headers[\"session-id\"] = sessionId;\n\t\t\t\tif (!headers[\"x-client-request-id\"]) headers[\"x-client-request-id\"] = sessionId;\n\t\t\t}\n\n\t\t\tconst inner = responsesApi.streamSimple(requestModel, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tonPayload: (payload) => reshapePayloadForRelay(payload, context, options?.onPayload, requestModel),\n\t\t\t});\n\n\t\t\tfor await (const event of inner) {\n\t\t\t\tstream.push(event);\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\t// Match examples/custom-provider-gitlab-duo error event shape.\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\terror: {\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: [],\n\t\t\t\t\tapi: model.api,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.id,\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t\tstopReason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\t\terrorMessage: formatError(error),\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t});\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Nudge the OpenAI Responses payload toward Codex CLI request shape for\n * transparent relays: instructions + input, store:false, no max_output_tokens /\n * prompt_cache_retention, verbosity + parallel_tool_calls.\n */\nasync function reshapePayloadForRelay(\n\tpayload: unknown,\n\tcontext: Context,\n\tuserOnPayload: SimpleStreamOptions[\"onPayload\"],\n\tmodel: Model<\"openai-responses\">,\n): Promise<unknown> {\n\tconst base =\n\t\tpayload && typeof payload === \"object\" && !Array.isArray(payload)\n\t\t\t? { ...(payload as Record<string, unknown>) }\n\t\t\t: ({} as Record<string, unknown>);\n\n\t// Always safe for ChatGPT/Codex-style backends.\n\tbase.store = false;\n\tbase.stream = true;\n\n\t// Codex CLI sends system prompt as `instructions`, not as a role message in input.\n\tconst { instructions, input } = extractInstructions(base.input, context.systemPrompt);\n\tif (instructions) base.instructions = instructions;\n\tif (input !== undefined) base.input = input;\n\n\t// Fields common on Codex CLI / rejected by many transparent Codex upstreams.\n\tif (!base.text || typeof base.text !== \"object\") {\n\t\tbase.text = { verbosity: \"low\" };\n\t}\n\tif (base.tool_choice === undefined) base.tool_choice = \"auto\";\n\tif (base.parallel_tool_calls === undefined) base.parallel_tool_calls = true;\n\n\t// Prefer encrypted reasoning content for multi-turn store:false sessions.\n\tconst include = Array.isArray(base.include) ? [...(base.include as unknown[])] : [];\n\tif (!include.includes(\"reasoning.encrypted_content\")) {\n\t\tinclude.push(\"reasoning.encrypted_content\");\n\t}\n\tbase.include = include;\n\n\t// Drop Platform-only fields that Codex OAuth endpoints often 400 on.\n\tdelete base.prompt_cache_retention;\n\tdelete base.max_output_tokens;\n\tdelete base.temperature;\n\tdelete base.top_p;\n\tdelete base.user;\n\tdelete base.metadata;\n\tdelete base.service_tier;\n\tdelete base.truncation;\n\tdelete base.context_management;\n\tdelete base.safety_identifier;\n\tdelete base.stream_options;\n\n\tif (userOnPayload) {\n\t\tconst next = await userOnPayload(base, model);\n\t\tif (next !== undefined) return next;\n\t}\n\treturn base;\n}\n\nfunction extractInstructions(\n\tinput: unknown,\n\tsystemPrompt: string | undefined,\n): { instructions?: string; input: unknown } {\n\t// Prefer context.systemPrompt (matches Codex stream path).\n\tif (systemPrompt && systemPrompt.length > 0) {\n\t\tconst stripped = stripLeadingSystemRoles(input);\n\t\treturn { instructions: systemPrompt, input: stripped ?? input };\n\t}\n\n\tif (!Array.isArray(input) || input.length === 0) {\n\t\treturn { input };\n\t}\n\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t\"role\" in first &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\tconst content = (first as { content?: unknown }).content;\n\t\tconst text =\n\t\t\ttypeof content === \"string\"\n\t\t\t\t? content\n\t\t\t\t: Array.isArray(content)\n\t\t\t\t\t? content\n\t\t\t\t\t\t\t.map((part) =>\n\t\t\t\t\t\t\t\tpart && typeof part === \"object\" && \"text\" in part\n\t\t\t\t\t\t\t\t\t? String((part as { text: unknown }).text)\n\t\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.join(\"\")\n\t\t\t\t\t: \"\";\n\t\treturn {\n\t\t\tinstructions: text || undefined,\n\t\t\tinput: input.slice(1),\n\t\t};\n\t}\n\n\treturn { input };\n}\n\nfunction stripLeadingSystemRoles(input: unknown): unknown {\n\tif (!Array.isArray(input) || input.length === 0) return input;\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\treturn input.slice(1);\n\t}\n\treturn input;\n}\n\nfunction clampCacheKey(sessionId: string | undefined): string | undefined {\n\tif (!sessionId) return undefined;\n\treturn sessionId.length <= 64 ? sessionId : sessionId.slice(0, 64);\n}\n\nexport function resolveResponsesUrl(baseUrl: string): string {\n\tconst normalized = baseUrl.trim().replace(/\\/+$/, \"\");\n\tif (!normalized) throw new Error(\"Model baseUrl is empty.\");\n\tif (normalized.endsWith(\"/responses\")) return normalized;\n\treturn `${normalized}/responses`;\n}\n\nexport function isRouterApi(api: string): boolean {\n\treturn api === ROUTER_API;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../src/extensions/router/stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACN,KAAK,GAAG,EACR,KAAK,OAAO,EACZ,iCAAiC,EACjC,KAAK,KAAK,EAEV,KAAK,mBAAmB,EACxB,MAAM,8BAA8B,CAAC;AAMtC,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,UAAU,CAAC,OAAO,iCAAiC,CAAC,CA0EtD;AA2KD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAK3D;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAEhD","sourcesContent":["/**\n * Codex-oriented Responses client for API relays.\n *\n * Follows Pi's documented custom-provider pattern (see coding-agent docs\n * providers.md / custom-provider.md and examples/custom-provider-gitlab-duo):\n * wrap a built-in pi-ai stream API from `@earendil-works/pi-ai/compat` instead of\n * reimplementing SSE or deep-importing internal modules.\n *\n * We use openAIResponsesApi (works with relay sk- keys) and reshape the request\n * payload toward Codex CLI style so transparent gateways receive a friendlier body.\n */\n\nimport {\n\ttype Api,\n\ttype Context,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\topenAIResponsesApi,\n\ttype SimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\n\nimport { DEFAULTS, formatError, ROUTER_API } from \"./constants.ts\";\n\nconst responsesApi = openAIResponsesApi();\n\nexport function streamRouterCodex(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): ReturnType<typeof createAssistantMessageEventStream> {\n\tconst stream = createAssistantMessageEventStream();\n\n\tvoid (async () => {\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);\n\n\t\t\t// Built-in Responses stream expects api \"openai-responses\" on the model object.\n\t\t\tconst requestModel = {\n\t\t\t\t...model,\n\t\t\t\tapi: \"openai-responses\" as const,\n\t\t\t\tcompat: {\n\t\t\t\t\tsupportsDeveloperRole: true,\n\t\t\t\t\t// Avoid underscore session_id header that strict proxies reject.\n\t\t\t\t\tsessionAffinityFormat: \"openai-nosession\" as const,\n\t\t\t\t\t// Codex-style upstreams reject prompt_cache_retention: \"24h\".\n\t\t\t\t\tsupportsLongCacheRetention: false,\n\t\t\t\t\t...(model.compat ?? {}),\n\t\t\t\t},\n\t\t\t} as Model<\"openai-responses\">;\n\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\toriginator: DEFAULTS.originator,\n\t\t\t\t...(options?.headers as Record<string, string> | undefined),\n\t\t\t};\n\n\t\t\t// Prefer hyphenated Codex-style session affinity when we have a session id.\n\t\t\tconst sessionId = clampCacheKey(options?.sessionId);\n\t\t\tif (sessionId) {\n\t\t\t\tif (!headers[\"session-id\"]) headers[\"session-id\"] = sessionId;\n\t\t\t\tif (!headers[\"x-client-request-id\"]) headers[\"x-client-request-id\"] = sessionId;\n\t\t\t}\n\n\t\t\tconst inner = responsesApi.streamSimple(requestModel, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tonPayload: (payload) => reshapePayloadForRelay(payload, context, options?.onPayload, requestModel),\n\t\t\t});\n\n\t\t\tfor await (const event of inner) {\n\t\t\t\tstream.push(event);\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\t// Match examples/custom-provider-gitlab-duo error event shape.\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\terror: {\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: [],\n\t\t\t\t\tapi: model.api,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.id,\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t\tstopReason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\t\terrorMessage: formatError(error),\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t});\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Nudge the OpenAI Responses payload toward Codex CLI request shape for\n * transparent relays: instructions + input, store:false, no max_output_tokens /\n * prompt_cache_retention, verbosity + parallel_tool_calls.\n */\nasync function reshapePayloadForRelay(\n\tpayload: unknown,\n\tcontext: Context,\n\tuserOnPayload: SimpleStreamOptions[\"onPayload\"],\n\tmodel: Model<\"openai-responses\">,\n): Promise<unknown> {\n\tconst base =\n\t\tpayload && typeof payload === \"object\" && !Array.isArray(payload)\n\t\t\t? { ...(payload as Record<string, unknown>) }\n\t\t\t: ({} as Record<string, unknown>);\n\n\t// Always safe for ChatGPT/Codex-style backends.\n\tbase.store = false;\n\tbase.stream = true;\n\n\t// Codex CLI sends system prompt as `instructions`, not as a role message in input.\n\tconst { instructions, input } = extractInstructions(base.input, context.systemPrompt);\n\tif (instructions) base.instructions = instructions;\n\tif (input !== undefined) base.input = input;\n\n\t// Codex CLI's ResponseItem serialization never emits `status` on replayed\n\t// message/function_call/function_call_output/reasoning items (only\n\t// local_shell_call has it), and output_text content has no `annotations`.\n\t// Strict Codex-schema gateways 400 on both (e.g. \"input[i].status:\n\t// unknown_parameter\"), while pi-ai emits them per the Platform schema.\n\tsanitizeInputItemsForCodex(base.input);\n\n\t// Fields common on Codex CLI / rejected by many transparent Codex upstreams.\n\tif (!base.text || typeof base.text !== \"object\") {\n\t\tbase.text = { verbosity: \"low\" };\n\t}\n\tif (base.tool_choice === undefined) base.tool_choice = \"auto\";\n\tif (base.parallel_tool_calls === undefined) base.parallel_tool_calls = true;\n\n\t// Prefer encrypted reasoning content for multi-turn store:false sessions.\n\tconst include = Array.isArray(base.include) ? [...(base.include as unknown[])] : [];\n\tif (!include.includes(\"reasoning.encrypted_content\")) {\n\t\tinclude.push(\"reasoning.encrypted_content\");\n\t}\n\tbase.include = include;\n\n\t// Drop Platform-only fields that Codex OAuth endpoints often 400 on.\n\tdelete base.prompt_cache_retention;\n\tdelete base.prompt_cache_options;\n\tdelete base.max_output_tokens;\n\tdelete base.temperature;\n\tdelete base.top_p;\n\tdelete base.user;\n\tdelete base.metadata;\n\tdelete base.service_tier;\n\tdelete base.truncation;\n\tdelete base.context_management;\n\tdelete base.safety_identifier;\n\tdelete base.stream_options;\n\n\tif (userOnPayload) {\n\t\tconst next = await userOnPayload(base, model);\n\t\tif (next !== undefined) return next;\n\t}\n\treturn base;\n}\n\n/**\n * Item types where Codex CLI's ResponseItem serialization has NO `status`\n * field (codex-rs/protocol/src/models.rs): Message, Reasoning, FunctionCall,\n * FunctionCallOutput, CustomToolCallOutput. Other item types either require\n * `status` (local_shell_call, tool_search_output, image_generation_call) or\n * accept it optionally (tool_search_call, custom_tool_call, web_search_call),\n * so we must not strip it there.\n */\nconst STATUS_LESS_ITEM_TYPES = new Set([\n\t\"message\",\n\t\"reasoning\",\n\t\"function_call\",\n\t\"function_call_output\",\n\t\"custom_tool_call_output\",\n]);\n\nfunction sanitizeInputItemsForCodex(input: unknown): void {\n\tif (!Array.isArray(input)) return;\n\tfor (const item of input) {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (typeof record.type === \"string\" && STATUS_LESS_ITEM_TYPES.has(record.type) && \"status\" in record) {\n\t\t\tdelete record.status;\n\t\t}\n\t\tif (Array.isArray(record.content)) {\n\t\t\tfor (const part of record.content) {\n\t\t\t\tif (\n\t\t\t\t\tpart &&\n\t\t\t\t\ttypeof part === \"object\" &&\n\t\t\t\t\t(part as { type?: string }).type === \"output_text\" &&\n\t\t\t\t\t\"annotations\" in part\n\t\t\t\t) {\n\t\t\t\t\tdelete (part as Record<string, unknown>).annotations;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction extractInstructions(\n\tinput: unknown,\n\tsystemPrompt: string | undefined,\n): { instructions?: string; input: unknown } {\n\t// Prefer context.systemPrompt (matches Codex stream path).\n\tif (systemPrompt && systemPrompt.length > 0) {\n\t\tconst stripped = stripLeadingSystemRoles(input);\n\t\treturn { instructions: systemPrompt, input: stripped ?? input };\n\t}\n\n\tif (!Array.isArray(input) || input.length === 0) {\n\t\treturn { input };\n\t}\n\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t\"role\" in first &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\tconst content = (first as { content?: unknown }).content;\n\t\tconst text =\n\t\t\ttypeof content === \"string\"\n\t\t\t\t? content\n\t\t\t\t: Array.isArray(content)\n\t\t\t\t\t? content\n\t\t\t\t\t\t\t.map((part) =>\n\t\t\t\t\t\t\t\tpart && typeof part === \"object\" && \"text\" in part\n\t\t\t\t\t\t\t\t\t? String((part as { text: unknown }).text)\n\t\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.join(\"\")\n\t\t\t\t\t: \"\";\n\t\treturn {\n\t\t\tinstructions: text || undefined,\n\t\t\tinput: input.slice(1),\n\t\t};\n\t}\n\n\treturn { input };\n}\n\nfunction stripLeadingSystemRoles(input: unknown): unknown {\n\tif (!Array.isArray(input) || input.length === 0) return input;\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\treturn input.slice(1);\n\t}\n\treturn input;\n}\n\nfunction clampCacheKey(sessionId: string | undefined): string | undefined {\n\tif (!sessionId) return undefined;\n\treturn sessionId.length <= 64 ? sessionId : sessionId.slice(0, 64);\n}\n\nexport function resolveResponsesUrl(baseUrl: string): string {\n\tconst normalized = baseUrl.trim().replace(/\\/+$/, \"\");\n\tif (!normalized) throw new Error(\"Model baseUrl is empty.\");\n\tif (normalized.endsWith(\"/responses\")) return normalized;\n\treturn `${normalized}/responses`;\n}\n\nexport function isRouterApi(api: string): boolean {\n\treturn api === ROUTER_API;\n}\n"]}
|
|
@@ -102,6 +102,12 @@ async function reshapePayloadForRelay(payload, context, userOnPayload, model) {
|
|
|
102
102
|
base.instructions = instructions;
|
|
103
103
|
if (input !== undefined)
|
|
104
104
|
base.input = input;
|
|
105
|
+
// Codex CLI's ResponseItem serialization never emits `status` on replayed
|
|
106
|
+
// message/function_call/function_call_output/reasoning items (only
|
|
107
|
+
// local_shell_call has it), and output_text content has no `annotations`.
|
|
108
|
+
// Strict Codex-schema gateways 400 on both (e.g. "input[i].status:
|
|
109
|
+
// unknown_parameter"), while pi-ai emits them per the Platform schema.
|
|
110
|
+
sanitizeInputItemsForCodex(base.input);
|
|
105
111
|
// Fields common on Codex CLI / rejected by many transparent Codex upstreams.
|
|
106
112
|
if (!base.text || typeof base.text !== "object") {
|
|
107
113
|
base.text = { verbosity: "low" };
|
|
@@ -118,6 +124,7 @@ async function reshapePayloadForRelay(payload, context, userOnPayload, model) {
|
|
|
118
124
|
base.include = include;
|
|
119
125
|
// Drop Platform-only fields that Codex OAuth endpoints often 400 on.
|
|
120
126
|
delete base.prompt_cache_retention;
|
|
127
|
+
delete base.prompt_cache_options;
|
|
121
128
|
delete base.max_output_tokens;
|
|
122
129
|
delete base.temperature;
|
|
123
130
|
delete base.top_p;
|
|
@@ -135,6 +142,43 @@ async function reshapePayloadForRelay(payload, context, userOnPayload, model) {
|
|
|
135
142
|
}
|
|
136
143
|
return base;
|
|
137
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Item types where Codex CLI's ResponseItem serialization has NO `status`
|
|
147
|
+
* field (codex-rs/protocol/src/models.rs): Message, Reasoning, FunctionCall,
|
|
148
|
+
* FunctionCallOutput, CustomToolCallOutput. Other item types either require
|
|
149
|
+
* `status` (local_shell_call, tool_search_output, image_generation_call) or
|
|
150
|
+
* accept it optionally (tool_search_call, custom_tool_call, web_search_call),
|
|
151
|
+
* so we must not strip it there.
|
|
152
|
+
*/
|
|
153
|
+
const STATUS_LESS_ITEM_TYPES = new Set([
|
|
154
|
+
"message",
|
|
155
|
+
"reasoning",
|
|
156
|
+
"function_call",
|
|
157
|
+
"function_call_output",
|
|
158
|
+
"custom_tool_call_output",
|
|
159
|
+
]);
|
|
160
|
+
function sanitizeInputItemsForCodex(input) {
|
|
161
|
+
if (!Array.isArray(input))
|
|
162
|
+
return;
|
|
163
|
+
for (const item of input) {
|
|
164
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
165
|
+
continue;
|
|
166
|
+
const record = item;
|
|
167
|
+
if (typeof record.type === "string" && STATUS_LESS_ITEM_TYPES.has(record.type) && "status" in record) {
|
|
168
|
+
delete record.status;
|
|
169
|
+
}
|
|
170
|
+
if (Array.isArray(record.content)) {
|
|
171
|
+
for (const part of record.content) {
|
|
172
|
+
if (part &&
|
|
173
|
+
typeof part === "object" &&
|
|
174
|
+
part.type === "output_text" &&
|
|
175
|
+
"annotations" in part) {
|
|
176
|
+
delete part.annotations;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
138
182
|
function extractInstructions(input, systemPrompt) {
|
|
139
183
|
// Prefer context.systemPrompt (matches Codex stream path).
|
|
140
184
|
if (systemPrompt && systemPrompt.length > 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/extensions/router/stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAGN,iCAAiC,EAEjC,kBAAkB,GAElB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEnE,MAAM,YAAY,GAAG,kBAAkB,EAAE,CAAC;AAE1C,MAAM,UAAU,iBAAiB,CAChC,KAAiB,EACjB,OAAgB,EAChB,OAA6B,EAC0B;IACvD,MAAM,MAAM,GAAG,iCAAiC,EAAE,CAAC;IAEnD,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;QACjB,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC;YAC/B,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;YAE3E,gFAAgF;YAChF,MAAM,YAAY,GAAG;gBACpB,GAAG,KAAK;gBACR,GAAG,EAAE,kBAA2B;gBAChC,MAAM,EAAE;oBACP,qBAAqB,EAAE,IAAI;oBAC3B,iEAAiE;oBACjE,qBAAqB,EAAE,kBAA2B;oBAClD,8DAA8D;oBAC9D,0BAA0B,EAAE,KAAK;oBACjC,GAAG,CAAC,KAAK,CAAC,MAAM,IAAI,EAAE,CAAC;iBACvB;aAC4B,CAAC;YAE/B,MAAM,OAAO,GAA2B;gBACvC,UAAU,EAAE,QAAQ,CAAC,UA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AAAA,CACjC;AAED,MAAM,UAAU,WAAW,CAAC,GAAW,EAAW;IACjD,OAAO,GAAG,KAAK,UAAU,CAAC;AAAA,CAC1B","sourcesContent":["/**\n * Codex-oriented Responses client for API relays.\n *\n * Follows Pi's documented custom-provider pattern (see coding-agent docs\n * providers.md / custom-provider.md and examples/custom-provider-gitlab-duo):\n * wrap a built-in pi-ai stream API from `@earendil-works/pi-ai/compat` instead of\n * reimplementing SSE or deep-importing internal modules.\n *\n * We use openAIResponsesApi (works with relay sk- keys) and reshape the request\n * payload toward Codex CLI style so transparent gateways receive a friendlier body.\n */\n\nimport {\n\ttype Api,\n\ttype Context,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\topenAIResponsesApi,\n\ttype SimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\n\nimport { DEFAULTS, formatError, ROUTER_API } from \"./constants.ts\";\n\nconst responsesApi = openAIResponsesApi();\n\nexport function streamRouterCodex(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): ReturnType<typeof createAssistantMessageEventStream> {\n\tconst stream = createAssistantMessageEventStream();\n\n\tvoid (async () => {\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);\n\n\t\t\t// Built-in Responses stream expects api \"openai-responses\" on the model object.\n\t\t\tconst requestModel = {\n\t\t\t\t...model,\n\t\t\t\tapi: \"openai-responses\" as const,\n\t\t\t\tcompat: {\n\t\t\t\t\tsupportsDeveloperRole: true,\n\t\t\t\t\t// Avoid underscore session_id header that strict proxies reject.\n\t\t\t\t\tsessionAffinityFormat: \"openai-nosession\" as const,\n\t\t\t\t\t// Codex-style upstreams reject prompt_cache_retention: \"24h\".\n\t\t\t\t\tsupportsLongCacheRetention: false,\n\t\t\t\t\t...(model.compat ?? {}),\n\t\t\t\t},\n\t\t\t} as Model<\"openai-responses\">;\n\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\toriginator: DEFAULTS.originator,\n\t\t\t\t...(options?.headers as Record<string, string> | undefined),\n\t\t\t};\n\n\t\t\t// Prefer hyphenated Codex-style session affinity when we have a session id.\n\t\t\tconst sessionId = clampCacheKey(options?.sessionId);\n\t\t\tif (sessionId) {\n\t\t\t\tif (!headers[\"session-id\"]) headers[\"session-id\"] = sessionId;\n\t\t\t\tif (!headers[\"x-client-request-id\"]) headers[\"x-client-request-id\"] = sessionId;\n\t\t\t}\n\n\t\t\tconst inner = responsesApi.streamSimple(requestModel, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tonPayload: (payload) => reshapePayloadForRelay(payload, context, options?.onPayload, requestModel),\n\t\t\t});\n\n\t\t\tfor await (const event of inner) {\n\t\t\t\tstream.push(event);\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\t// Match examples/custom-provider-gitlab-duo error event shape.\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\terror: {\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: [],\n\t\t\t\t\tapi: model.api,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.id,\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t\tstopReason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\t\terrorMessage: formatError(error),\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t});\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Nudge the OpenAI Responses payload toward Codex CLI request shape for\n * transparent relays: instructions + input, store:false, no max_output_tokens /\n * prompt_cache_retention, verbosity + parallel_tool_calls.\n */\nasync function reshapePayloadForRelay(\n\tpayload: unknown,\n\tcontext: Context,\n\tuserOnPayload: SimpleStreamOptions[\"onPayload\"],\n\tmodel: Model<\"openai-responses\">,\n): Promise<unknown> {\n\tconst base =\n\t\tpayload && typeof payload === \"object\" && !Array.isArray(payload)\n\t\t\t? { ...(payload as Record<string, unknown>) }\n\t\t\t: ({} as Record<string, unknown>);\n\n\t// Always safe for ChatGPT/Codex-style backends.\n\tbase.store = false;\n\tbase.stream = true;\n\n\t// Codex CLI sends system prompt as `instructions`, not as a role message in input.\n\tconst { instructions, input } = extractInstructions(base.input, context.systemPrompt);\n\tif (instructions) base.instructions = instructions;\n\tif (input !== undefined) base.input = input;\n\n\t// Fields common on Codex CLI / rejected by many transparent Codex upstreams.\n\tif (!base.text || typeof base.text !== \"object\") {\n\t\tbase.text = { verbosity: \"low\" };\n\t}\n\tif (base.tool_choice === undefined) base.tool_choice = \"auto\";\n\tif (base.parallel_tool_calls === undefined) base.parallel_tool_calls = true;\n\n\t// Prefer encrypted reasoning content for multi-turn store:false sessions.\n\tconst include = Array.isArray(base.include) ? [...(base.include as unknown[])] : [];\n\tif (!include.includes(\"reasoning.encrypted_content\")) {\n\t\tinclude.push(\"reasoning.encrypted_content\");\n\t}\n\tbase.include = include;\n\n\t// Drop Platform-only fields that Codex OAuth endpoints often 400 on.\n\tdelete base.prompt_cache_retention;\n\tdelete base.max_output_tokens;\n\tdelete base.temperature;\n\tdelete base.top_p;\n\tdelete base.user;\n\tdelete base.metadata;\n\tdelete base.service_tier;\n\tdelete base.truncation;\n\tdelete base.context_management;\n\tdelete base.safety_identifier;\n\tdelete base.stream_options;\n\n\tif (userOnPayload) {\n\t\tconst next = await userOnPayload(base, model);\n\t\tif (next !== undefined) return next;\n\t}\n\treturn base;\n}\n\nfunction extractInstructions(\n\tinput: unknown,\n\tsystemPrompt: string | undefined,\n): { instructions?: string; input: unknown } {\n\t// Prefer context.systemPrompt (matches Codex stream path).\n\tif (systemPrompt && systemPrompt.length > 0) {\n\t\tconst stripped = stripLeadingSystemRoles(input);\n\t\treturn { instructions: systemPrompt, input: stripped ?? input };\n\t}\n\n\tif (!Array.isArray(input) || input.length === 0) {\n\t\treturn { input };\n\t}\n\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t\"role\" in first &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\tconst content = (first as { content?: unknown }).content;\n\t\tconst text =\n\t\t\ttypeof content === \"string\"\n\t\t\t\t? content\n\t\t\t\t: Array.isArray(content)\n\t\t\t\t\t? content\n\t\t\t\t\t\t\t.map((part) =>\n\t\t\t\t\t\t\t\tpart && typeof part === \"object\" && \"text\" in part\n\t\t\t\t\t\t\t\t\t? String((part as { text: unknown }).text)\n\t\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.join(\"\")\n\t\t\t\t\t: \"\";\n\t\treturn {\n\t\t\tinstructions: text || undefined,\n\t\t\tinput: input.slice(1),\n\t\t};\n\t}\n\n\treturn { input };\n}\n\nfunction stripLeadingSystemRoles(input: unknown): unknown {\n\tif (!Array.isArray(input) || input.length === 0) return input;\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\treturn input.slice(1);\n\t}\n\treturn input;\n}\n\nfunction clampCacheKey(sessionId: string | undefined): string | undefined {\n\tif (!sessionId) return undefined;\n\treturn sessionId.length <= 64 ? sessionId : sessionId.slice(0, 64);\n}\n\nexport function resolveResponsesUrl(baseUrl: string): string {\n\tconst normalized = baseUrl.trim().replace(/\\/+$/, \"\");\n\tif (!normalized) throw new Error(\"Model baseUrl is empty.\");\n\tif (normalized.endsWith(\"/responses\")) return normalized;\n\treturn `${normalized}/responses`;\n}\n\nexport function isRouterApi(api: string): boolean {\n\treturn api === ROUTER_API;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/extensions/router/stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAGN,iCAAiC,EAEjC,kBAAkB,GAElB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEnE,MAAM,YAAY,GAAG,kBAAkB,EAAE,CAAC;AAE1C,MAAM,UAAU,iBAAiB,CAChC,KAAiB,EACjB,OAAgB,EAChB,OAA6B,EAC0B;IACvD,MAAM,MAAM,GAAG,iCAAiC,EAAE,CAAC;IAEnD,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;QACjB,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC;YAC/B,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;YAE3E,gFAAgF;YAChF,MAAM,YAAY,GAAG;gBACpB,GAAG,KAAK;gBACR,GAAG,EAAE,kBAA2B;gBAChC,MAAM,EAAE;oBACP,qBAAqB,EAAE,IAAI;oBAC3B,iEAAiE;oBACjE,qBAAqB,EAAE,kBAA2B;oBAClD,8DAA8D;oBAC9D,0BAA0B,EAAE,KAAK;oBACjC,GAAG,CAAC,KAAK,CAAC,MAAM,IAAI,EAAE,CAAC;iBACvB;aAC4B,CAAC;YAE/B,MAAM,OAAO,GAA2B;gBACvC,UAAU,EAAE,QAAQ,CAAC,UAAU;gBAC/B,GAAI,OAAO,EAAE,OAA8C;aAC3D,CAAC;YAEF,4EAA4E;YAC5E,MAAM,SAAS,GAAG,aAAa,CAA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,uBAAuB,CAAC,KAAc,EAAW;IACzD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IACvB,IACC,KAAK;QACL,OAAO,KAAK,KAAK,QAAQ;QACzB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACrB,CAAE,KAA2B,CAAC,IAAI,KAAK,QAAQ,IAAK,KAA2B,CAAC,IAAI,KAAK,WAAW,CAAC,EACpG,CAAC;QACF,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb;AAED,SAAS,aAAa,CAAC,SAA6B,EAAsB;IACzE,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,OAAO,SAAS,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAAA,CACnE;AAED,MAAM,UAAU,mBAAmB,CAAC,OAAe,EAAU;IAC5D,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IACtD,IAAI,CAAC,UAAU;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC5D,IAAI,UAAU,CAAC,QAAQ,CAAC,YAAY,CAAC;QAAE,OAAO,UAAU,CAAC;IACzD,OAAO,GAAG,UAAU,YAAY,CAAC;AAAA,CACjC;AAED,MAAM,UAAU,WAAW,CAAC,GAAW,EAAW;IACjD,OAAO,GAAG,KAAK,UAAU,CAAC;AAAA,CAC1B","sourcesContent":["/**\n * Codex-oriented Responses client for API relays.\n *\n * Follows Pi's documented custom-provider pattern (see coding-agent docs\n * providers.md / custom-provider.md and examples/custom-provider-gitlab-duo):\n * wrap a built-in pi-ai stream API from `@earendil-works/pi-ai/compat` instead of\n * reimplementing SSE or deep-importing internal modules.\n *\n * We use openAIResponsesApi (works with relay sk- keys) and reshape the request\n * payload toward Codex CLI style so transparent gateways receive a friendlier body.\n */\n\nimport {\n\ttype Api,\n\ttype Context,\n\tcreateAssistantMessageEventStream,\n\ttype Model,\n\topenAIResponsesApi,\n\ttype SimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\n\nimport { DEFAULTS, formatError, ROUTER_API } from \"./constants.ts\";\n\nconst responsesApi = openAIResponsesApi();\n\nexport function streamRouterCodex(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): ReturnType<typeof createAssistantMessageEventStream> {\n\tconst stream = createAssistantMessageEventStream();\n\n\tvoid (async () => {\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);\n\n\t\t\t// Built-in Responses stream expects api \"openai-responses\" on the model object.\n\t\t\tconst requestModel = {\n\t\t\t\t...model,\n\t\t\t\tapi: \"openai-responses\" as const,\n\t\t\t\tcompat: {\n\t\t\t\t\tsupportsDeveloperRole: true,\n\t\t\t\t\t// Avoid underscore session_id header that strict proxies reject.\n\t\t\t\t\tsessionAffinityFormat: \"openai-nosession\" as const,\n\t\t\t\t\t// Codex-style upstreams reject prompt_cache_retention: \"24h\".\n\t\t\t\t\tsupportsLongCacheRetention: false,\n\t\t\t\t\t...(model.compat ?? {}),\n\t\t\t\t},\n\t\t\t} as Model<\"openai-responses\">;\n\n\t\t\tconst headers: Record<string, string> = {\n\t\t\t\toriginator: DEFAULTS.originator,\n\t\t\t\t...(options?.headers as Record<string, string> | undefined),\n\t\t\t};\n\n\t\t\t// Prefer hyphenated Codex-style session affinity when we have a session id.\n\t\t\tconst sessionId = clampCacheKey(options?.sessionId);\n\t\t\tif (sessionId) {\n\t\t\t\tif (!headers[\"session-id\"]) headers[\"session-id\"] = sessionId;\n\t\t\t\tif (!headers[\"x-client-request-id\"]) headers[\"x-client-request-id\"] = sessionId;\n\t\t\t}\n\n\t\t\tconst inner = responsesApi.streamSimple(requestModel, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tonPayload: (payload) => reshapePayloadForRelay(payload, context, options?.onPayload, requestModel),\n\t\t\t});\n\n\t\t\tfor await (const event of inner) {\n\t\t\t\tstream.push(event);\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\t// Match examples/custom-provider-gitlab-duo error event shape.\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\terror: {\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: [],\n\t\t\t\t\tapi: model.api,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.id,\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t\tstopReason: options?.signal?.aborted ? \"aborted\" : \"error\",\n\t\t\t\t\terrorMessage: formatError(error),\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t});\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Nudge the OpenAI Responses payload toward Codex CLI request shape for\n * transparent relays: instructions + input, store:false, no max_output_tokens /\n * prompt_cache_retention, verbosity + parallel_tool_calls.\n */\nasync function reshapePayloadForRelay(\n\tpayload: unknown,\n\tcontext: Context,\n\tuserOnPayload: SimpleStreamOptions[\"onPayload\"],\n\tmodel: Model<\"openai-responses\">,\n): Promise<unknown> {\n\tconst base =\n\t\tpayload && typeof payload === \"object\" && !Array.isArray(payload)\n\t\t\t? { ...(payload as Record<string, unknown>) }\n\t\t\t: ({} as Record<string, unknown>);\n\n\t// Always safe for ChatGPT/Codex-style backends.\n\tbase.store = false;\n\tbase.stream = true;\n\n\t// Codex CLI sends system prompt as `instructions`, not as a role message in input.\n\tconst { instructions, input } = extractInstructions(base.input, context.systemPrompt);\n\tif (instructions) base.instructions = instructions;\n\tif (input !== undefined) base.input = input;\n\n\t// Codex CLI's ResponseItem serialization never emits `status` on replayed\n\t// message/function_call/function_call_output/reasoning items (only\n\t// local_shell_call has it), and output_text content has no `annotations`.\n\t// Strict Codex-schema gateways 400 on both (e.g. \"input[i].status:\n\t// unknown_parameter\"), while pi-ai emits them per the Platform schema.\n\tsanitizeInputItemsForCodex(base.input);\n\n\t// Fields common on Codex CLI / rejected by many transparent Codex upstreams.\n\tif (!base.text || typeof base.text !== \"object\") {\n\t\tbase.text = { verbosity: \"low\" };\n\t}\n\tif (base.tool_choice === undefined) base.tool_choice = \"auto\";\n\tif (base.parallel_tool_calls === undefined) base.parallel_tool_calls = true;\n\n\t// Prefer encrypted reasoning content for multi-turn store:false sessions.\n\tconst include = Array.isArray(base.include) ? [...(base.include as unknown[])] : [];\n\tif (!include.includes(\"reasoning.encrypted_content\")) {\n\t\tinclude.push(\"reasoning.encrypted_content\");\n\t}\n\tbase.include = include;\n\n\t// Drop Platform-only fields that Codex OAuth endpoints often 400 on.\n\tdelete base.prompt_cache_retention;\n\tdelete base.prompt_cache_options;\n\tdelete base.max_output_tokens;\n\tdelete base.temperature;\n\tdelete base.top_p;\n\tdelete base.user;\n\tdelete base.metadata;\n\tdelete base.service_tier;\n\tdelete base.truncation;\n\tdelete base.context_management;\n\tdelete base.safety_identifier;\n\tdelete base.stream_options;\n\n\tif (userOnPayload) {\n\t\tconst next = await userOnPayload(base, model);\n\t\tif (next !== undefined) return next;\n\t}\n\treturn base;\n}\n\n/**\n * Item types where Codex CLI's ResponseItem serialization has NO `status`\n * field (codex-rs/protocol/src/models.rs): Message, Reasoning, FunctionCall,\n * FunctionCallOutput, CustomToolCallOutput. Other item types either require\n * `status` (local_shell_call, tool_search_output, image_generation_call) or\n * accept it optionally (tool_search_call, custom_tool_call, web_search_call),\n * so we must not strip it there.\n */\nconst STATUS_LESS_ITEM_TYPES = new Set([\n\t\"message\",\n\t\"reasoning\",\n\t\"function_call\",\n\t\"function_call_output\",\n\t\"custom_tool_call_output\",\n]);\n\nfunction sanitizeInputItemsForCodex(input: unknown): void {\n\tif (!Array.isArray(input)) return;\n\tfor (const item of input) {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (typeof record.type === \"string\" && STATUS_LESS_ITEM_TYPES.has(record.type) && \"status\" in record) {\n\t\t\tdelete record.status;\n\t\t}\n\t\tif (Array.isArray(record.content)) {\n\t\t\tfor (const part of record.content) {\n\t\t\t\tif (\n\t\t\t\t\tpart &&\n\t\t\t\t\ttypeof part === \"object\" &&\n\t\t\t\t\t(part as { type?: string }).type === \"output_text\" &&\n\t\t\t\t\t\"annotations\" in part\n\t\t\t\t) {\n\t\t\t\t\tdelete (part as Record<string, unknown>).annotations;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction extractInstructions(\n\tinput: unknown,\n\tsystemPrompt: string | undefined,\n): { instructions?: string; input: unknown } {\n\t// Prefer context.systemPrompt (matches Codex stream path).\n\tif (systemPrompt && systemPrompt.length > 0) {\n\t\tconst stripped = stripLeadingSystemRoles(input);\n\t\treturn { instructions: systemPrompt, input: stripped ?? input };\n\t}\n\n\tif (!Array.isArray(input) || input.length === 0) {\n\t\treturn { input };\n\t}\n\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t\"role\" in first &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\tconst content = (first as { content?: unknown }).content;\n\t\tconst text =\n\t\t\ttypeof content === \"string\"\n\t\t\t\t? content\n\t\t\t\t: Array.isArray(content)\n\t\t\t\t\t? content\n\t\t\t\t\t\t\t.map((part) =>\n\t\t\t\t\t\t\t\tpart && typeof part === \"object\" && \"text\" in part\n\t\t\t\t\t\t\t\t\t? String((part as { text: unknown }).text)\n\t\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.join(\"\")\n\t\t\t\t\t: \"\";\n\t\treturn {\n\t\t\tinstructions: text || undefined,\n\t\t\tinput: input.slice(1),\n\t\t};\n\t}\n\n\treturn { input };\n}\n\nfunction stripLeadingSystemRoles(input: unknown): unknown {\n\tif (!Array.isArray(input) || input.length === 0) return input;\n\tconst first = input[0];\n\tif (\n\t\tfirst &&\n\t\ttypeof first === \"object\" &&\n\t\t!Array.isArray(first) &&\n\t\t((first as { role?: string }).role === \"system\" || (first as { role?: string }).role === \"developer\")\n\t) {\n\t\treturn input.slice(1);\n\t}\n\treturn input;\n}\n\nfunction clampCacheKey(sessionId: string | undefined): string | undefined {\n\tif (!sessionId) return undefined;\n\treturn sessionId.length <= 64 ? sessionId : sessionId.slice(0, 64);\n}\n\nexport function resolveResponsesUrl(baseUrl: string): string {\n\tconst normalized = baseUrl.trim().replace(/\\/+$/, \"\");\n\tif (!normalized) throw new Error(\"Model baseUrl is empty.\");\n\tif (normalized.endsWith(\"/responses\")) return normalized;\n\treturn `${normalized}/responses`;\n}\n\nexport function isRouterApi(api: string): boolean {\n\treturn api === ROUTER_API;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity.d.ts","sourceRoot":"","sources":["../../../src/extensions/subagent/activity.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,KAAK,EA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AI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAgBhE;AAgBD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAS/D;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,GAAG,SAAS,GAAG,MAAM,CAMvE;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAM5E;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,YAAY,EAAE,EAAE,QAAQ,EAAE,YAAY,GAAG,IAAI,CAUvF;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAWvE;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,CAoBrD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai\";\nimport { ACTIVITY_LIMIT, ACTIVITY_TEXT_LIMIT, LIVE_TEXT_LIMIT, SINGLE_OUTPUT_LIMIT } from \"./constants.ts\";\nimport type { SubagentUsage, ToolActivity } from \"./types.ts\";\n\nexport function emptyUsage(): SubagentUsage {\n\treturn {\n\t\tturns: 0,\n\t\ttoolUses: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: 0,\n\t};\n}\n\nexport function addUsage(target: SubagentUsage, usage: Usage | undefined): void {\n\tif (!usage) return;\n\ttarget.input += usage.input ?? 0;\n\ttarget.output += usage.output ?? 0;\n\ttarget.cacheRead += usage.cacheRead ?? 0;\n\ttarget.cacheWrite += usage.cacheWrite ?? 0;\n\ttarget.totalTokens += usage.totalTokens ?? 0;\n\ttarget.cost += usage.cost?.total ?? 0;\n\t// Watermark, not a sum: the latest request's total is the context size,\n\t// and it can shrink again after the worker auto-compacts.\n\tif (usage.totalTokens) target.contextTokens = usage.totalTokens;\n}\n\nexport function mergeUsage(target: SubagentUsage, source: SubagentUsage): void {\n\ttarget.turns += source.turns;\n\ttarget.toolUses += source.toolUses;\n\ttarget.input += source.input;\n\ttarget.output += source.output;\n\ttarget.cacheRead += source.cacheRead;\n\ttarget.cacheWrite += source.cacheWrite;\n\ttarget.totalTokens += source.totalTokens;\n\ttarget.cost += source.cost;\n\tif (source.contextTokens) {\n\t\ttarget.contextTokens = Math.max(target.contextTokens ?? 0, source.contextTokens);\n\t}\n}\n\nexport function toNestedUsage(usage: SubagentUsage): Usage {\n\treturn {\n\t\tinput: usage.input,\n\t\toutput: usage.output,\n\t\tcacheRead: usage.cacheRead,\n\t\tcacheWrite: usage.cacheWrite,\n\t\ttotalTokens: usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotal: usage.cost,\n\t\t},\n\t};\n}\n\n// Iterates code points so a surrogate pair is never split in half.\nexport function utf8Prefix(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tlet output = \"\";\n\tlet bytes = 0;\n\tfor (const character of text) {\n\t\tconst characterBytes = Buffer.byteLength(character, \"utf8\");\n\t\tif (bytes + characterBytes > maxBytes) break;\n\t\toutput += character;\n\t\tbytes += characterBytes;\n\t}\n\treturn output;\n}\n\nexport function boundText(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tlet output = utf8Prefix(text, maxBytes);\n\tfor (let attempt = 0; attempt < 8; attempt++) {\n\t\tconst omitted = Buffer.byteLength(text, \"utf8\") - Buffer.byteLength(output, \"utf8\");\n\t\tconst notice = `\\n\\n[Output truncated: ${omitted} bytes omitted.]`;\n\t\tconst available = maxBytes - Buffer.byteLength(notice, \"utf8\");\n\t\tif (available <= 0) return utf8Prefix(\"[Output truncated.]\", maxBytes);\n\t\tconst next = utf8Prefix(text, available);\n\t\tif (next === output) return `${output}${notice}`;\n\t\toutput = next;\n\t}\n\tconst omitted = Buffer.byteLength(text, \"utf8\") - Buffer.byteLength(output, \"utf8\");\n\tconst notice = `\\n\\n[Output truncated: ${omitted} bytes omitted.]`;\n\treturn `${utf8Prefix(output, Math.max(0, maxBytes - Buffer.byteLength(notice, \"utf8\")))}${notice}`;\n}\n\nfunction utf8Suffix(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tconst characters: string[] = [];\n\tlet bytes = 0;\n\tfor (const character of Array.from(text).reverse()) {\n\t\tconst characterBytes = Buffer.byteLength(character, \"utf8\");\n\t\tif (bytes + characterBytes > maxBytes) break;\n\t\tcharacters.push(character);\n\t\tbytes += characterBytes;\n\t}\n\treturn characters.reverse().join(\"\");\n}\n\nexport function tailText(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tconst noticeText = \"[Earlier output omitted.]\";\n\tconst notice = `${noticeText}\\n`;\n\tconst available = maxBytes - Buffer.byteLength(notice, \"utf8\");\n\tif (available <= 0) return utf8Prefix(noticeText, maxBytes);\n\tconst output = utf8Suffix(text, available);\n\treturn output ? `${notice}${output}` : utf8Prefix(noticeText, maxBytes);\n}\n\nexport function assistantText(message: AgentMessage | undefined): string {\n\tif (!message || message.role !== \"assistant\") return \"\";\n\treturn message.content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\nexport function finalAssistantText(messages: readonly AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst text = assistantText(messages[index]);\n\t\tif (text) return boundText(text, SINGLE_OUTPUT_LIMIT);\n\t}\n\treturn \"\";\n}\n\nexport function appendActivity(activities: ToolActivity[], activity: ToolActivity): void {\n\tactivities.push(activity);\n\twhile (activities.length > ACTIVITY_LIMIT) activities.shift();\n\twhile (\n\t\tactivities.reduce((total, item) => total + item.summary.length + (item.resultSummary?.length ?? 0), 0) >\n\t\tACTIVITY_TEXT_LIMIT\n\t) {\n\t\tif (activities.length <= 1) break;\n\t\tactivities.shift();\n\t}\n}\n\nexport function setLiveText(text: string): string {\n\treturn tailText(text, LIVE_TEXT_LIMIT);\n}\n\nexport function activitySummary(toolName: string, args: unknown): string {\n\tif (!args || typeof args !== \"object\" || Array.isArray(args)) return toolName;\n\tconst input = args as Record<string, unknown>;\n\tconst path =\n\t\ttypeof input.path === \"string\" ? input.path : typeof input.file_path === \"string\" ? input.file_path : undefined;\n\tif (toolName === \"bash\" && typeof input.command === \"string\")\n\t\treturn `Run ${boundText(input.command.replace(/\\s+/gu, \" \"), 160)}`;\n\tif (path) return `${toolName} ${boundText(path, 180)}`;\n\tif (toolName === \"grep\" && typeof input.pattern === \"string\") return `Search ${boundText(input.pattern, 120)}`;\n\tif (toolName === \"find\" && typeof input.pattern === \"string\") return `Find ${boundText(input.pattern, 120)}`;\n\treturn toolName;\n}\n\nexport function resultSummary(result: unknown): string {\n\tif (!result || typeof result !== \"object\") return \"\";\n\tconst content = (result as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn boundText(\n\t\tcontent\n\t\t\t.filter((part): part is { type: \"text\"; text: string } => {\n\t\t\t\treturn Boolean(\n\t\t\t\t\tpart &&\n\t\t\t\t\t\ttypeof part === \"object\" &&\n\t\t\t\t\t\t(part as { type?: unknown }).type === \"text\" &&\n\t\t\t\t\t\ttypeof (part as { text?: unknown }).text === \"string\",\n\t\t\t\t);\n\t\t\t})\n\t\t\t.map((part) => part.text)\n\t\t\t.join(\"\\n\")\n\t\t\t.replace(/\\s+/gu, \" \")\n\t\t\t.trim(),\n\t\t240,\n\t);\n}\n"]}
|
|
@@ -92,13 +92,34 @@ export function boundText(text, maxBytes) {
|
|
|
92
92
|
const notice = `\n\n[Output truncated: ${omitted} bytes omitted.]`;
|
|
93
93
|
return `${utf8Prefix(output, Math.max(0, maxBytes - Buffer.byteLength(notice, "utf8")))}${notice}`;
|
|
94
94
|
}
|
|
95
|
+
function utf8Suffix(text, maxBytes) {
|
|
96
|
+
if (maxBytes <= 0)
|
|
97
|
+
return "";
|
|
98
|
+
if (Buffer.byteLength(text, "utf8") <= maxBytes)
|
|
99
|
+
return text;
|
|
100
|
+
const characters = [];
|
|
101
|
+
let bytes = 0;
|
|
102
|
+
for (const character of Array.from(text).reverse()) {
|
|
103
|
+
const characterBytes = Buffer.byteLength(character, "utf8");
|
|
104
|
+
if (bytes + characterBytes > maxBytes)
|
|
105
|
+
break;
|
|
106
|
+
characters.push(character);
|
|
107
|
+
bytes += characterBytes;
|
|
108
|
+
}
|
|
109
|
+
return characters.reverse().join("");
|
|
110
|
+
}
|
|
95
111
|
export function tailText(text, maxBytes) {
|
|
112
|
+
if (maxBytes <= 0)
|
|
113
|
+
return "";
|
|
96
114
|
if (Buffer.byteLength(text, "utf8") <= maxBytes)
|
|
97
115
|
return text;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
116
|
+
const noticeText = "[Earlier output omitted.]";
|
|
117
|
+
const notice = `${noticeText}\n`;
|
|
118
|
+
const available = maxBytes - Buffer.byteLength(notice, "utf8");
|
|
119
|
+
if (available <= 0)
|
|
120
|
+
return utf8Prefix(noticeText, maxBytes);
|
|
121
|
+
const output = utf8Suffix(text, available);
|
|
122
|
+
return output ? `${notice}${output}` : utf8Prefix(noticeText, maxBytes);
|
|
102
123
|
}
|
|
103
124
|
export function assistantText(message) {
|
|
104
125
|
if (!message || message.role !== "assistant")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity.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I,CAAC,IAAI,CAAC;SACxB,IAAI,CAAC,IAAI,CAAC;SACV,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,IAAI,EAAE,EACR,GAAG,CACH,CAAC;AAAA,CACF","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai\";\nimport { ACTIVITY_LIMIT, ACTIVITY_TEXT_LIMIT, LIVE_TEXT_LIMIT, SINGLE_OUTPUT_LIMIT } from \"./constants.ts\";\nimport type { SubagentUsage, ToolActivity } from \"./types.ts\";\n\nexport function emptyUsage(): SubagentUsage {\n\treturn {\n\t\tturns: 0,\n\t\ttoolUses: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: 0,\n\t};\n}\n\nexport function addUsage(target: SubagentUsage, usage: Usage | undefined): void {\n\tif (!usage) return;\n\ttarget.input += usage.input ?? 0;\n\ttarget.output += usage.output ?? 0;\n\ttarget.cacheRead += usage.cacheRead ?? 0;\n\ttarget.cacheWrite += usage.cacheWrite ?? 0;\n\ttarget.totalTokens += usage.totalTokens ?? 0;\n\ttarget.cost += usage.cost?.total ?? 0;\n\t// Watermark, not a sum: the latest request's total is the context size,\n\t// and it can shrink again after the worker auto-compacts.\n\tif (usage.totalTokens) target.contextTokens = usage.totalTokens;\n}\n\nexport function mergeUsage(target: SubagentUsage, source: SubagentUsage): void {\n\ttarget.turns += source.turns;\n\ttarget.toolUses += source.toolUses;\n\ttarget.input += source.input;\n\ttarget.output += source.output;\n\ttarget.cacheRead += source.cacheRead;\n\ttarget.cacheWrite += source.cacheWrite;\n\ttarget.totalTokens += source.totalTokens;\n\ttarget.cost += source.cost;\n\tif (source.contextTokens) {\n\t\ttarget.contextTokens = Math.max(target.contextTokens ?? 0, source.contextTokens);\n\t}\n}\n\nexport function toNestedUsage(usage: SubagentUsage): Usage {\n\treturn {\n\t\tinput: usage.input,\n\t\toutput: usage.output,\n\t\tcacheRead: usage.cacheRead,\n\t\tcacheWrite: usage.cacheWrite,\n\t\ttotalTokens: usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotal: usage.cost,\n\t\t},\n\t};\n}\n\n// Iterates code points so a surrogate pair is never split in half.\nexport function utf8Prefix(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tlet output = \"\";\n\tlet bytes = 0;\n\tfor (const character of text) {\n\t\tconst characterBytes = Buffer.byteLength(character, \"utf8\");\n\t\tif (bytes + characterBytes > maxBytes) break;\n\t\toutput += character;\n\t\tbytes += characterBytes;\n\t}\n\treturn output;\n}\n\nexport function boundText(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tlet output = utf8Prefix(text, maxBytes);\n\tfor (let attempt = 0; attempt < 8; attempt++) {\n\t\tconst omitted = Buffer.byteLength(text, \"utf8\") - Buffer.byteLength(output, \"utf8\");\n\t\tconst notice = `\\n\\n[Output truncated: ${omitted} bytes omitted.]`;\n\t\tconst available = maxBytes - Buffer.byteLength(notice, \"utf8\");\n\t\tif (available <= 0) return utf8Prefix(\"[Output truncated.]\", maxBytes);\n\t\tconst next = utf8Prefix(text, available);\n\t\tif (next === output) return `${output}${notice}`;\n\t\toutput = next;\n\t}\n\tconst omitted = Buffer.byteLength(text, \"utf8\") - Buffer.byteLength(output, \"utf8\");\n\tconst notice = `\\n\\n[Output truncated: ${omitted} bytes omitted.]`;\n\treturn `${utf8Prefix(output, Math.max(0, maxBytes - Buffer.byteLength(notice, \"utf8\")))}${notice}`;\n}\n\nexport function tailText(text: string, maxBytes: number): string {\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tlet output = text.slice(-maxBytes);\n\twhile (Buffer.byteLength(output, \"utf8\") > maxBytes) output = output.slice(1);\n\treturn `[Earlier output omitted.]\\n${output}`;\n}\n\nexport function assistantText(message: AgentMessage | undefined): string {\n\tif (!message || message.role !== \"assistant\") return \"\";\n\treturn message.content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\nexport function finalAssistantText(messages: readonly AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst text = assistantText(messages[index]);\n\t\tif (text) return boundText(text, SINGLE_OUTPUT_LIMIT);\n\t}\n\treturn \"\";\n}\n\nexport function appendActivity(activities: ToolActivity[], activity: ToolActivity): void {\n\tactivities.push(activity);\n\twhile (activities.length > ACTIVITY_LIMIT) activities.shift();\n\twhile (\n\t\tactivities.reduce((total, item) => total + item.summary.length + (item.resultSummary?.length ?? 0), 0) >\n\t\tACTIVITY_TEXT_LIMIT\n\t) {\n\t\tif (activities.length <= 1) break;\n\t\tactivities.shift();\n\t}\n}\n\nexport function setLiveText(text: string): string {\n\treturn tailText(text, LIVE_TEXT_LIMIT);\n}\n\nexport function activitySummary(toolName: string, args: unknown): string {\n\tif (!args || typeof args !== \"object\" || Array.isArray(args)) return toolName;\n\tconst input = args as Record<string, unknown>;\n\tconst path =\n\t\ttypeof input.path === \"string\" ? input.path : typeof input.file_path === \"string\" ? input.file_path : undefined;\n\tif (toolName === \"bash\" && typeof input.command === \"string\")\n\t\treturn `Run ${boundText(input.command.replace(/\\s+/gu, \" \"), 160)}`;\n\tif (path) return `${toolName} ${boundText(path, 180)}`;\n\tif (toolName === \"grep\" && typeof input.pattern === \"string\") return `Search ${boundText(input.pattern, 120)}`;\n\tif (toolName === \"find\" && typeof input.pattern === \"string\") return `Find ${boundText(input.pattern, 120)}`;\n\treturn toolName;\n}\n\nexport function resultSummary(result: unknown): string {\n\tif (!result || typeof result !== \"object\") return \"\";\n\tconst content = (result as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn boundText(\n\t\tcontent\n\t\t\t.filter((part): part is { type: \"text\"; text: string } => {\n\t\t\t\treturn Boolean(\n\t\t\t\t\tpart &&\n\t\t\t\t\t\ttypeof part === \"object\" &&\n\t\t\t\t\t\t(part as { type?: unknown }).type === \"text\" &&\n\t\t\t\t\t\ttypeof (part as { text?: unknown }).text === \"string\",\n\t\t\t\t);\n\t\t\t})\n\t\t\t.map((part) => part.text)\n\t\t\t.join(\"\\n\")\n\t\t\t.replace(/\\s+/gu, \" \")\n\t\t\t.trim(),\n\t\t240,\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"activity.js","sourceRoot":"","sources":["../../../src/extensions/subagent/activity.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAG3G,MAAM,UAAU,UAAU,GAAkB;IAC3C,OAAO;QACN,KAAK,EAAE,CAAC;QACR,QAAQ,EAAE,CAAC;QACX,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,IAAI,EAAE,CAAC;KACP,CAAC;AAAA,CACF;AAED,MAAM,UAAU,QAAQ,CAAC,MAAqB,EAAE,KAAwB,EAAQ;IAC/E,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC;IACjC,MAAM,CAAC,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,CAAC;IACnC,MAAM,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,IAAI,CAAC,CAAC;IACzC,MAAM,CAAC,UAAU,IAAI,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC;IAC3C,MAAM,CAAC,WAAW,IAAI,KAAK,CAAC,WAAW,I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AAI,KAAK,MAAM;YAC5C,OAAQ,IAA2B,CAAC,IAAI,KAAK,QAAQ,CACtD,CAAC;IAAA,CACF,CAAC;SACD,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;SACxB,IAAI,CAAC,IAAI,CAAC;SACV,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;SACrB,IAAI,EAAE,EACR,GAAG,CACH,CAAC;AAAA,CACF","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai\";\nimport { ACTIVITY_LIMIT, ACTIVITY_TEXT_LIMIT, LIVE_TEXT_LIMIT, SINGLE_OUTPUT_LIMIT } from \"./constants.ts\";\nimport type { SubagentUsage, ToolActivity } from \"./types.ts\";\n\nexport function emptyUsage(): SubagentUsage {\n\treturn {\n\t\tturns: 0,\n\t\ttoolUses: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: 0,\n\t};\n}\n\nexport function addUsage(target: SubagentUsage, usage: Usage | undefined): void {\n\tif (!usage) return;\n\ttarget.input += usage.input ?? 0;\n\ttarget.output += usage.output ?? 0;\n\ttarget.cacheRead += usage.cacheRead ?? 0;\n\ttarget.cacheWrite += usage.cacheWrite ?? 0;\n\ttarget.totalTokens += usage.totalTokens ?? 0;\n\ttarget.cost += usage.cost?.total ?? 0;\n\t// Watermark, not a sum: the latest request's total is the context size,\n\t// and it can shrink again after the worker auto-compacts.\n\tif (usage.totalTokens) target.contextTokens = usage.totalTokens;\n}\n\nexport function mergeUsage(target: SubagentUsage, source: SubagentUsage): void {\n\ttarget.turns += source.turns;\n\ttarget.toolUses += source.toolUses;\n\ttarget.input += source.input;\n\ttarget.output += source.output;\n\ttarget.cacheRead += source.cacheRead;\n\ttarget.cacheWrite += source.cacheWrite;\n\ttarget.totalTokens += source.totalTokens;\n\ttarget.cost += source.cost;\n\tif (source.contextTokens) {\n\t\ttarget.contextTokens = Math.max(target.contextTokens ?? 0, source.contextTokens);\n\t}\n}\n\nexport function toNestedUsage(usage: SubagentUsage): Usage {\n\treturn {\n\t\tinput: usage.input,\n\t\toutput: usage.output,\n\t\tcacheRead: usage.cacheRead,\n\t\tcacheWrite: usage.cacheWrite,\n\t\ttotalTokens: usage.totalTokens,\n\t\tcost: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotal: usage.cost,\n\t\t},\n\t};\n}\n\n// Iterates code points so a surrogate pair is never split in half.\nexport function utf8Prefix(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tlet output = \"\";\n\tlet bytes = 0;\n\tfor (const character of text) {\n\t\tconst characterBytes = Buffer.byteLength(character, \"utf8\");\n\t\tif (bytes + characterBytes > maxBytes) break;\n\t\toutput += character;\n\t\tbytes += characterBytes;\n\t}\n\treturn output;\n}\n\nexport function boundText(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tlet output = utf8Prefix(text, maxBytes);\n\tfor (let attempt = 0; attempt < 8; attempt++) {\n\t\tconst omitted = Buffer.byteLength(text, \"utf8\") - Buffer.byteLength(output, \"utf8\");\n\t\tconst notice = `\\n\\n[Output truncated: ${omitted} bytes omitted.]`;\n\t\tconst available = maxBytes - Buffer.byteLength(notice, \"utf8\");\n\t\tif (available <= 0) return utf8Prefix(\"[Output truncated.]\", maxBytes);\n\t\tconst next = utf8Prefix(text, available);\n\t\tif (next === output) return `${output}${notice}`;\n\t\toutput = next;\n\t}\n\tconst omitted = Buffer.byteLength(text, \"utf8\") - Buffer.byteLength(output, \"utf8\");\n\tconst notice = `\\n\\n[Output truncated: ${omitted} bytes omitted.]`;\n\treturn `${utf8Prefix(output, Math.max(0, maxBytes - Buffer.byteLength(notice, \"utf8\")))}${notice}`;\n}\n\nfunction utf8Suffix(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tconst characters: string[] = [];\n\tlet bytes = 0;\n\tfor (const character of Array.from(text).reverse()) {\n\t\tconst characterBytes = Buffer.byteLength(character, \"utf8\");\n\t\tif (bytes + characterBytes > maxBytes) break;\n\t\tcharacters.push(character);\n\t\tbytes += characterBytes;\n\t}\n\treturn characters.reverse().join(\"\");\n}\n\nexport function tailText(text: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\tif (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n\tconst noticeText = \"[Earlier output omitted.]\";\n\tconst notice = `${noticeText}\\n`;\n\tconst available = maxBytes - Buffer.byteLength(notice, \"utf8\");\n\tif (available <= 0) return utf8Prefix(noticeText, maxBytes);\n\tconst output = utf8Suffix(text, available);\n\treturn output ? `${notice}${output}` : utf8Prefix(noticeText, maxBytes);\n}\n\nexport function assistantText(message: AgentMessage | undefined): string {\n\tif (!message || message.role !== \"assistant\") return \"\";\n\treturn message.content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\nexport function finalAssistantText(messages: readonly AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst text = assistantText(messages[index]);\n\t\tif (text) return boundText(text, SINGLE_OUTPUT_LIMIT);\n\t}\n\treturn \"\";\n}\n\nexport function appendActivity(activities: ToolActivity[], activity: ToolActivity): void {\n\tactivities.push(activity);\n\twhile (activities.length > ACTIVITY_LIMIT) activities.shift();\n\twhile (\n\t\tactivities.reduce((total, item) => total + item.summary.length + (item.resultSummary?.length ?? 0), 0) >\n\t\tACTIVITY_TEXT_LIMIT\n\t) {\n\t\tif (activities.length <= 1) break;\n\t\tactivities.shift();\n\t}\n}\n\nexport function setLiveText(text: string): string {\n\treturn tailText(text, LIVE_TEXT_LIMIT);\n}\n\nexport function activitySummary(toolName: string, args: unknown): string {\n\tif (!args || typeof args !== \"object\" || Array.isArray(args)) return toolName;\n\tconst input = args as Record<string, unknown>;\n\tconst path =\n\t\ttypeof input.path === \"string\" ? input.path : typeof input.file_path === \"string\" ? input.file_path : undefined;\n\tif (toolName === \"bash\" && typeof input.command === \"string\")\n\t\treturn `Run ${boundText(input.command.replace(/\\s+/gu, \" \"), 160)}`;\n\tif (path) return `${toolName} ${boundText(path, 180)}`;\n\tif (toolName === \"grep\" && typeof input.pattern === \"string\") return `Search ${boundText(input.pattern, 120)}`;\n\tif (toolName === \"find\" && typeof input.pattern === \"string\") return `Find ${boundText(input.pattern, 120)}`;\n\treturn toolName;\n}\n\nexport function resultSummary(result: unknown): string {\n\tif (!result || typeof result !== \"object\") return \"\";\n\tconst content = (result as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn boundText(\n\t\tcontent\n\t\t\t.filter((part): part is { type: \"text\"; text: string } => {\n\t\t\t\treturn Boolean(\n\t\t\t\t\tpart &&\n\t\t\t\t\t\ttypeof part === \"object\" &&\n\t\t\t\t\t\t(part as { type?: unknown }).type === \"text\" &&\n\t\t\t\t\t\ttypeof (part as { text?: unknown }).text === \"string\",\n\t\t\t\t);\n\t\t\t})\n\t\t\t.map((part) => part.text)\n\t\t\t.join(\"\\n\")\n\t\t\t.replace(/\\s+/gu, \" \")\n\t\t\t.trim(),\n\t\t240,\n\t);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../../../src/extensions/subagent/agents.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAoC,oBAAoB,EAAe,MAAM,YAAY,CAAC;AAwItG,wBAAgB,cAAc,CAC7B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;IAAE,cAAc,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,GACrD,oBAAoB,CAiBtB;AAED,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,oBAAoB,GAAG,MAAM,CAkD/E","sourcesContent":["import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../config.ts\";\nimport { parseFrontmatter } from \"../../utils/frontmatter.ts\";\nimport { utf8Prefix } from \"./activity.ts\";\nimport { BUILTIN_TOOL_NAMES, DEFAULT_AGENT_TOOLS, EXPLORER_TOOLS } from \"./constants.ts\";\nimport type { AgentDefinition, AgentDiagnostic, AgentDiscoveryResult, AgentSource } from \"./types.ts\";\n\nconst AGENT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,79}$/u;\nconst BUILTIN_TOOL_SET = new Set<string>(BUILTIN_TOOL_NAMES);\nconst TOOL_DESCRIPTION_AGENT_LIST_LIMIT = 8_000;\nconst TOOL_DESCRIPTION_AGENT_SUMMARY_LIMIT = 480;\n\nconst BUILTIN_AGENTS: AgentDefinition[] = [\n\t{\n\t\tname: \"general\",\n\t\tdescription: \"General-purpose implementation agent with coding tools\",\n\t\ttools: [...DEFAULT_AGENT_TOOLS],\n\t\tsystemPrompt: [\n\t\t\t\"Work independently on the delegated task from start to finish.\",\n\t\t\t\"Inspect relevant repository instructions before changing files.\",\n\t\t\t\"Prefer editing existing files; never create documentation files unless the task explicitly asks for them.\",\n\t\t\t\"Keep changes focused, run appropriate verification, and report exact paths, checks, blockers, and remaining risks.\",\n\t\t].join(\"\\n\"),\n\t\tsource: \"builtin\",\n\t\tfilePath: \"<builtin:general>\",\n\t\tbackend: \"sdk\",\n\t},\n\t{\n\t\tname: \"explorer\",\n\t\tdescription:\n\t\t\t'Fast read-only agent for finding files, searching code, and answering codebase questions. State thoroughness in the prompt: \"quick\" for a targeted lookup, \"medium\" for checking likely related locations, or \"very thorough\" for exhaustive sweeps across locations and naming conventions',\n\t\ttools: [...EXPLORER_TOOLS],\n\t\tsystemPrompt: [\n\t\t\t\"You are a fast read-only exploration agent; return findings as quickly as possible.\",\n\t\t\t\"Explore the delegated question without modifying files.\",\n\t\t\t\"Use read and search tools to gather exact evidence, batching independent searches and reads instead of running them one at a time.\",\n\t\t\t\"Match the depth the caller requested: quick targets the direct question, medium checks likely related locations, and very thorough sweeps multiple locations and naming conventions.\",\n\t\t\t\"Return concise findings with precise paths, symbols, relationships, and unresolved uncertainties.\",\n\t\t].join(\"\\n\"),\n\t\tsource: \"builtin\",\n\t\tfilePath: \"<builtin:explorer>\",\n\t\tbackend: \"sdk\",\n\t},\n];\n\nfunction isDirectory(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction findNearestProjectAgentsDir(cwd: string): string | undefined {\n\tlet current = cwd;\n\twhile (true) {\n\t\tconst candidate = join(current, CONFIG_DIR_NAME, \"agents\");\n\t\tif (isDirectory(candidate)) return candidate;\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return undefined;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction parseTools(raw: string | undefined, filePath: string): string[] {\n\tif (!raw?.trim()) return [...DEFAULT_AGENT_TOOLS];\n\tconst tools = [\n\t\t...new Set(\n\t\t\traw\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((tool) => tool.trim())\n\t\t\t\t.filter(Boolean),\n\t\t),\n\t];\n\tconst unsupported = tools.filter((tool) => !BUILTIN_TOOL_SET.has(tool));\n\tif (unsupported.length > 0) {\n\t\tthrow new Error(`Unsupported tool(s) ${unsupported.join(\", \")} in ${filePath}.`);\n\t}\n\treturn tools;\n}\n\n// Frontmatter model/thinking keys are intentionally ignored: agent files\n// travel across machines (project repos), so a pinned model rarely exists\n// in the reader's environment. Model and thinking come from /agents\n// overrides or default to the parent session.\nfunction parseAgentFile(filePath: string, source: Exclude<AgentSource, \"builtin\">): AgentDefinition {\n\tconst content = readFileSync(filePath, \"utf8\");\n\tconst { frontmatter, body } = parseFrontmatter<Record<string, string>>(content);\n\tconst name = frontmatter.name?.trim() ?? \"\";\n\tconst description = frontmatter.description?.trim() ?? \"\";\n\tif (!name) throw new Error(\"Missing required frontmatter field: name.\");\n\tif (!AGENT_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`Agent name \"${name}\" must use lowercase letters, digits, hyphens, or underscores.`);\n\t}\n\tif (!description) throw new Error(\"Missing required frontmatter field: description.\");\n\tif (!body.trim()) throw new Error(\"Agent prompt body must not be empty.\");\n\tconst backend = frontmatter.backend?.trim();\n\tif (backend && backend !== \"sdk\") throw new Error(`Backend \"${backend}\" is not implemented; use \"sdk\".`);\n\treturn {\n\t\tname,\n\t\tdescription,\n\t\ttools: parseTools(frontmatter.tools, filePath),\n\t\tsystemPrompt: body.trim(),\n\t\tsource,\n\t\tfilePath,\n\t\tbackend: \"sdk\",\n\t};\n}\n\nfunction loadAgentDirectory(\n\tdir: string,\n\tsource: Exclude<AgentSource, \"builtin\">,\n): { agents: AgentDefinition[]; diagnostics: AgentDiagnostic[] } {\n\tif (!existsSync(dir)) return { agents: [], diagnostics: [] };\n\tlet entries: Dirent[];\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));\n\t} catch (error) {\n\t\treturn {\n\t\t\tagents: [],\n\t\t\tdiagnostics: [{ path: dir, source, message: error instanceof Error ? error.message : String(error) }],\n\t\t};\n\t}\n\tconst agents: AgentDefinition[] = [];\n\tconst diagnostics: AgentDiagnostic[] = [];\n\tfor (const entry of entries) {\n\t\tif (!entry.name.endsWith(\".md\") || (!entry.isFile() && !entry.isSymbolicLink())) continue;\n\t\tconst filePath = join(dir, entry.name);\n\t\ttry {\n\t\t\tagents.push(parseAgentFile(filePath, source));\n\t\t} catch (error) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: filePath,\n\t\t\t\tsource,\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t}\n\t}\n\treturn { agents, diagnostics };\n}\n\nexport function discoverAgents(\n\tcwd: string,\n\toptions: { projectTrusted: boolean; agentDir?: string },\n): AgentDiscoveryResult {\n\tconst userDir = join(options.agentDir ?? getAgentDir(), \"agents\");\n\tconst projectAgentsDir = findNearestProjectAgentsDir(cwd);\n\tconst user = loadAgentDirectory(userDir, \"user\");\n\tconst project =\n\t\toptions.projectTrusted && projectAgentsDir\n\t\t\t? loadAgentDirectory(projectAgentsDir, \"project\")\n\t\t\t: { agents: [], diagnostics: [] };\n\tconst agents = new Map(BUILTIN_AGENTS.map((agent) => [agent.name, { ...agent, tools: [...agent.tools] }]));\n\tfor (const agent of user.agents) agents.set(agent.name, agent);\n\tfor (const agent of project.agents) agents.set(agent.name, agent);\n\treturn {\n\t\tagents: [...agents.values()],\n\t\tdiagnostics: [...user.diagnostics, ...project.diagnostics],\n\t\tprojectAgentsDir,\n\t\tprojectAgentsTrusted: options.projectTrusted,\n\t};\n}\n\nexport function subagentToolDescription(discovery: AgentDiscoveryResult): string {\n\tconst agentLines: string[] = [];\n\tlet agentListLength = 0;\n\tfor (const [index, agent] of discovery.agents.entries()) {\n\t\tconst normalizedDescription = agent.description.replace(/\\s+/gu, \" \").trim();\n\t\tconst description =\n\t\t\tBuffer.byteLength(normalizedDescription, \"utf8\") <= TOOL_DESCRIPTION_AGENT_SUMMARY_LIMIT\n\t\t\t\t? normalizedDescription\n\t\t\t\t: `${utf8Prefix(normalizedDescription, TOOL_DESCRIPTION_AGENT_SUMMARY_LIMIT - Buffer.byteLength(\"…\", \"utf8\"))}…`;\n\t\tconst defaultLabel = agent.name === \"general\" ? \" (default)\" : \"\";\n\t\tconst tools = agent.tools.length > 0 ? agent.tools.join(\", \") : \"none\";\n\t\tconst line = `- ${agent.name}${defaultLabel}: ${description} (Tools: ${tools})`;\n\t\tconst lineLength = Buffer.byteLength(line, \"utf8\") + 1;\n\t\tif (agentListLength + lineLength > TOOL_DESCRIPTION_AGENT_LIST_LIMIT) {\n\t\t\tlet omitted = discovery.agents.length - index;\n\t\t\tlet notice = `- ${omitted} additional profile${omitted === 1 ? \"\" : \"s\"} omitted from this bounded description; /agents lists every profile.`;\n\t\t\twhile (\n\t\t\t\tagentLines.length > 0 &&\n\t\t\t\tagentListLength + Buffer.byteLength(notice, \"utf8\") + 1 > TOOL_DESCRIPTION_AGENT_LIST_LIMIT\n\t\t\t) {\n\t\t\t\tconst removed = agentLines.pop();\n\t\t\t\tif (!removed) break;\n\t\t\t\tagentListLength -= Buffer.byteLength(removed, \"utf8\") + 1;\n\t\t\t\tomitted++;\n\t\t\t\tnotice = `- ${omitted} additional profile${omitted === 1 ? \"\" : \"s\"} omitted from this bounded description; /agents lists every profile.`;\n\t\t\t}\n\t\t\tagentLines.push(notice);\n\t\t\tbreak;\n\t\t}\n\t\tagentLines.push(line);\n\t\tagentListLength += lineLength;\n\t}\n\n\treturn [\n\t\t\"Delegate bounded work to isolated one-shot subagents. Choose exactly one mode: prompt for one task, or tasks for independent parallel work. For sequential work, call this tool again with the previous result folded into the next briefing.\",\n\t\t\"\",\n\t\t\"Available agent profiles:\",\n\t\t...agentLines,\n\t\t\"\",\n\t\t\"When not to delegate:\",\n\t\t\"- Read a known file directly with read, or search for a known symbol directly with grep.\",\n\t\t\"- Do not delegate a trivial task when the coordination overhead exceeds the work.\",\n\t\t\"\",\n\t\t\"Writing the briefing:\",\n\t\t\"- Brief the worker like a capable colleague entering the project now: include the objective, relevant context, exact paths or symbols already known, constraints, and expected output.\",\n\t\t\"- Never delegate understanding with vague instructions such as 'fix this based on your findings'; state what must be investigated or changed and whether the worker should research, implement, or review.\",\n\t\t\"- Ask for a concise report when only findings are needed. Workers cannot see the parent conversation or ask the end user questions.\",\n\t\t\"\",\n\t\t\"Subagent results are reports for you to interpret and relay. Surface the important findings, changes, verification, and unresolved risks to the user.\",\n\t].join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../../../src/extensions/subagent/agents.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAoC,oBAAoB,EAAe,MAAM,YAAY,CAAC;AA4ItG,wBAAgB,cAAc,CAC7B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;IAAE,cAAc,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,GACrD,oBAAoB,CAiBtB;AAED,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,oBAAoB,GAAG,MAAM,CAqD/E","sourcesContent":["import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../config.ts\";\nimport { parseFrontmatter } from \"../../utils/frontmatter.ts\";\nimport { utf8Prefix } from \"./activity.ts\";\nimport { BUILTIN_TOOL_NAMES, DEFAULT_AGENT_TOOLS, EXPLORER_TOOLS, MAX_CONCURRENCY, MAX_TASKS } from \"./constants.ts\";\nimport type { AgentDefinition, AgentDiagnostic, AgentDiscoveryResult, AgentSource } from \"./types.ts\";\n\nconst AGENT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,79}$/u;\nconst BUILTIN_TOOL_SET = new Set<string>(BUILTIN_TOOL_NAMES);\nconst TOOL_DESCRIPTION_AGENT_LIST_LIMIT = 8_000;\nconst TOOL_DESCRIPTION_AGENT_SUMMARY_LIMIT = 480;\n\nconst BUILTIN_AGENTS: AgentDefinition[] = [\n\t{\n\t\tname: \"general\",\n\t\tdescription:\n\t\t\t\"Implementation agent for bounded coding tasks: edits, fixes, refactors, and verification in a scoped area. Use when the task changes files; use explorer for read-only questions\",\n\t\ttools: [...DEFAULT_AGENT_TOOLS],\n\t\tsystemPrompt: [\n\t\t\t\"Work independently on the delegated task from start to finish.\",\n\t\t\t\"Inspect relevant repository instructions before changing files.\",\n\t\t\t\"Prefer editing existing files; never create documentation files unless the task explicitly asks for them.\",\n\t\t\t\"Keep changes focused, run appropriate verification, and report exact paths, checks, blockers, and remaining risks.\",\n\t\t].join(\"\\n\"),\n\t\tsource: \"builtin\",\n\t\tfilePath: \"<builtin:general>\",\n\t\tbackend: \"sdk\",\n\t},\n\t{\n\t\tname: \"explorer\",\n\t\tdescription:\n\t\t\t'Fast read-only agent for finding files, searching code, and answering codebase questions. Can inspect git history (log, blame, diff) via read-only bash. State thoroughness in the prompt: \"quick\" for a targeted lookup, \"medium\" for checking likely related locations, or \"very thorough\" for exhaustive sweeps across locations and naming conventions',\n\t\ttools: [...EXPLORER_TOOLS],\n\t\tsystemPrompt: [\n\t\t\t\"You are a fast read-only exploration agent; return findings as quickly as possible.\",\n\t\t\t\"Explore the delegated question without modifying files.\",\n\t\t\t\"Use read and search tools to gather exact evidence, batching independent searches and reads instead of running them one at a time.\",\n\t\t\t\"bash is for read-only inspection only: git log/diff/blame/show/status, ls, wc, head, tail, cat, and similar.\",\n\t\t\t\"Never run anything that modifies state: no file creation or deletion, no redirect (>, >>) or heredoc writes, no temp files, no git commands that write (add, commit, checkout, restore, stash, clean), no installs, no network access.\",\n\t\t\t\"Match the depth the caller requested: quick targets the direct question, medium checks likely related locations, and very thorough sweeps multiple locations and naming conventions.\",\n\t\t\t\"Return concise findings with precise paths, symbols, relationships, and unresolved uncertainties.\",\n\t\t].join(\"\\n\"),\n\t\tsource: \"builtin\",\n\t\tfilePath: \"<builtin:explorer>\",\n\t\tbackend: \"sdk\",\n\t\tomitContextFiles: true,\n\t},\n];\n\nfunction isDirectory(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction findNearestProjectAgentsDir(cwd: string): string | undefined {\n\tlet current = cwd;\n\twhile (true) {\n\t\tconst candidate = join(current, CONFIG_DIR_NAME, \"agents\");\n\t\tif (isDirectory(candidate)) return candidate;\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) return undefined;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction parseTools(raw: string | undefined, filePath: string): string[] {\n\tif (!raw?.trim()) return [...DEFAULT_AGENT_TOOLS];\n\tconst tools = [\n\t\t...new Set(\n\t\t\traw\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((tool) => tool.trim())\n\t\t\t\t.filter(Boolean),\n\t\t),\n\t];\n\tconst unsupported = tools.filter((tool) => !BUILTIN_TOOL_SET.has(tool));\n\tif (unsupported.length > 0) {\n\t\tthrow new Error(`Unsupported tool(s) ${unsupported.join(\", \")} in ${filePath}.`);\n\t}\n\treturn tools;\n}\n\n// Frontmatter model/thinking keys are intentionally ignored: agent files\n// travel across machines (project repos), so a pinned model rarely exists\n// in the reader's environment. Model and thinking come from /agents\n// overrides or default to the parent session.\nfunction parseAgentFile(filePath: string, source: Exclude<AgentSource, \"builtin\">): AgentDefinition {\n\tconst content = readFileSync(filePath, \"utf8\");\n\tconst { frontmatter, body } = parseFrontmatter<Record<string, string>>(content);\n\tconst name = frontmatter.name?.trim() ?? \"\";\n\tconst description = frontmatter.description?.trim() ?? \"\";\n\tif (!name) throw new Error(\"Missing required frontmatter field: name.\");\n\tif (!AGENT_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`Agent name \"${name}\" must use lowercase letters, digits, hyphens, or underscores.`);\n\t}\n\tif (!description) throw new Error(\"Missing required frontmatter field: description.\");\n\tif (!body.trim()) throw new Error(\"Agent prompt body must not be empty.\");\n\tconst backend = frontmatter.backend?.trim();\n\tif (backend && backend !== \"sdk\") throw new Error(`Backend \"${backend}\" is not implemented; use \"sdk\".`);\n\treturn {\n\t\tname,\n\t\tdescription,\n\t\ttools: parseTools(frontmatter.tools, filePath),\n\t\tsystemPrompt: body.trim(),\n\t\tsource,\n\t\tfilePath,\n\t\tbackend: \"sdk\",\n\t};\n}\n\nfunction loadAgentDirectory(\n\tdir: string,\n\tsource: Exclude<AgentSource, \"builtin\">,\n): { agents: AgentDefinition[]; diagnostics: AgentDiagnostic[] } {\n\tif (!existsSync(dir)) return { agents: [], diagnostics: [] };\n\tlet entries: Dirent[];\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));\n\t} catch (error) {\n\t\treturn {\n\t\t\tagents: [],\n\t\t\tdiagnostics: [{ path: dir, source, message: error instanceof Error ? error.message : String(error) }],\n\t\t};\n\t}\n\tconst agents: AgentDefinition[] = [];\n\tconst diagnostics: AgentDiagnostic[] = [];\n\tfor (const entry of entries) {\n\t\tif (!entry.name.endsWith(\".md\") || (!entry.isFile() && !entry.isSymbolicLink())) continue;\n\t\tconst filePath = join(dir, entry.name);\n\t\ttry {\n\t\t\tagents.push(parseAgentFile(filePath, source));\n\t\t} catch (error) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: filePath,\n\t\t\t\tsource,\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t}\n\t}\n\treturn { agents, diagnostics };\n}\n\nexport function discoverAgents(\n\tcwd: string,\n\toptions: { projectTrusted: boolean; agentDir?: string },\n): AgentDiscoveryResult {\n\tconst userDir = join(options.agentDir ?? getAgentDir(), \"agents\");\n\tconst projectAgentsDir = findNearestProjectAgentsDir(cwd);\n\tconst user = loadAgentDirectory(userDir, \"user\");\n\tconst project =\n\t\toptions.projectTrusted && projectAgentsDir\n\t\t\t? loadAgentDirectory(projectAgentsDir, \"project\")\n\t\t\t: { agents: [], diagnostics: [] };\n\tconst agents = new Map(BUILTIN_AGENTS.map((agent) => [agent.name, { ...agent, tools: [...agent.tools] }]));\n\tfor (const agent of user.agents) agents.set(agent.name, agent);\n\tfor (const agent of project.agents) agents.set(agent.name, agent);\n\treturn {\n\t\tagents: [...agents.values()],\n\t\tdiagnostics: [...user.diagnostics, ...project.diagnostics],\n\t\tprojectAgentsDir,\n\t\tprojectAgentsTrusted: options.projectTrusted,\n\t};\n}\n\nexport function subagentToolDescription(discovery: AgentDiscoveryResult): string {\n\tconst agentLines: string[] = [];\n\tlet agentListLength = 0;\n\tfor (const [index, agent] of discovery.agents.entries()) {\n\t\tconst normalizedDescription = agent.description.replace(/\\s+/gu, \" \").trim();\n\t\tconst description =\n\t\t\tBuffer.byteLength(normalizedDescription, \"utf8\") <= TOOL_DESCRIPTION_AGENT_SUMMARY_LIMIT\n\t\t\t\t? normalizedDescription\n\t\t\t\t: `${utf8Prefix(normalizedDescription, TOOL_DESCRIPTION_AGENT_SUMMARY_LIMIT - Buffer.byteLength(\"…\", \"utf8\"))}…`;\n\t\tconst defaultLabel = agent.name === \"general\" ? \" (default)\" : \"\";\n\t\tconst tools = agent.tools.length > 0 ? agent.tools.join(\", \") : \"none\";\n\t\tconst line = `- ${agent.name}${defaultLabel}: ${description} (Tools: ${tools})`;\n\t\tconst lineLength = Buffer.byteLength(line, \"utf8\") + 1;\n\t\tif (agentListLength + lineLength > TOOL_DESCRIPTION_AGENT_LIST_LIMIT) {\n\t\t\tlet omitted = discovery.agents.length - index;\n\t\t\tlet notice = `- ${omitted} additional profile${omitted === 1 ? \"\" : \"s\"} omitted from this bounded description; /agents lists every profile.`;\n\t\t\twhile (\n\t\t\t\tagentLines.length > 0 &&\n\t\t\t\tagentListLength + Buffer.byteLength(notice, \"utf8\") + 1 > TOOL_DESCRIPTION_AGENT_LIST_LIMIT\n\t\t\t) {\n\t\t\t\tconst removed = agentLines.pop();\n\t\t\t\tif (!removed) break;\n\t\t\t\tagentListLength -= Buffer.byteLength(removed, \"utf8\") + 1;\n\t\t\t\tomitted++;\n\t\t\t\tnotice = `- ${omitted} additional profile${omitted === 1 ? \"\" : \"s\"} omitted from this bounded description; /agents lists every profile.`;\n\t\t\t}\n\t\t\tagentLines.push(notice);\n\t\t\tbreak;\n\t\t}\n\t\tagentLines.push(line);\n\t\tagentListLength += lineLength;\n\t}\n\n\treturn [\n\t\t`Delegate bounded work to isolated one-shot subagents. Delegation keeps intermediate tool output (file dumps, search results) out of your context: you receive only the final report. Choose exactly one mode: prompt for one task, or tasks for independent parallel work (up to ${MAX_TASKS} per call; ${MAX_CONCURRENCY} run concurrently, the rest queue). For sequential work, call this tool again with the previous result folded into the next briefing.`,\n\t\t\"\",\n\t\t\"Available agent profiles:\",\n\t\t...agentLines,\n\t\t\"\",\n\t\t\"When not to delegate:\",\n\t\t\"- Read a known file directly with read, or search for a known symbol directly with grep.\",\n\t\t\"- Prefer direct tools when a directed lookup answers the question; delegate when the investigation will clearly take more than ~3 searches or would flood your context with intermediate output.\",\n\t\t\"- Do not delegate a trivial task when the coordination overhead exceeds the work.\",\n\t\t\"\",\n\t\t\"Writing the briefing:\",\n\t\t\"- Brief the worker like a capable colleague entering the project now: include the objective, relevant context, exact paths or symbols already known, constraints, and expected output.\",\n\t\t\"- Never delegate understanding with vague instructions such as 'fix this based on your findings'; state what must be investigated or changed and whether the worker should research, implement, or review.\",\n\t\t\"- Lookups: hand over the exact command or file. Investigations: hand over the question — prescribed steps become dead weight when the premise is wrong.\",\n\t\t'- If you need a short answer, say so (e.g. \"report in under 200 words\"). Workers cannot see the parent conversation or ask the end user questions.',\n\t\t'- Example briefing (explorer): \"Quick: which commit introduced the retry loop in src/net/client.ts? Use git log/blame; report the hash and a one-line summary.\"',\n\t\t\"\",\n\t\t\"The subagent's report is not shown to the user. Interpret it and relay the important findings, changes, verification, and unresolved risks in your own reply.\",\n\t].join(\"\\n\");\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { dirname, join } from "node:path";
|
|
|
3
3
|
import { CONFIG_DIR_NAME, getAgentDir } from "../../config.js";
|
|
4
4
|
import { parseFrontmatter } from "../../utils/frontmatter.js";
|
|
5
5
|
import { utf8Prefix } from "./activity.js";
|
|
6
|
-
import { BUILTIN_TOOL_NAMES, DEFAULT_AGENT_TOOLS, EXPLORER_TOOLS } from "./constants.js";
|
|
6
|
+
import { BUILTIN_TOOL_NAMES, DEFAULT_AGENT_TOOLS, EXPLORER_TOOLS, MAX_CONCURRENCY, MAX_TASKS } from "./constants.js";
|
|
7
7
|
const AGENT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,79}$/u;
|
|
8
8
|
const BUILTIN_TOOL_SET = new Set(BUILTIN_TOOL_NAMES);
|
|
9
9
|
const TOOL_DESCRIPTION_AGENT_LIST_LIMIT = 8_000;
|
|
@@ -11,7 +11,7 @@ const TOOL_DESCRIPTION_AGENT_SUMMARY_LIMIT = 480;
|
|
|
11
11
|
const BUILTIN_AGENTS = [
|
|
12
12
|
{
|
|
13
13
|
name: "general",
|
|
14
|
-
description: "
|
|
14
|
+
description: "Implementation agent for bounded coding tasks: edits, fixes, refactors, and verification in a scoped area. Use when the task changes files; use explorer for read-only questions",
|
|
15
15
|
tools: [...DEFAULT_AGENT_TOOLS],
|
|
16
16
|
systemPrompt: [
|
|
17
17
|
"Work independently on the delegated task from start to finish.",
|
|
@@ -25,18 +25,21 @@ const BUILTIN_AGENTS = [
|
|
|
25
25
|
},
|
|
26
26
|
{
|
|
27
27
|
name: "explorer",
|
|
28
|
-
description: 'Fast read-only agent for finding files, searching code, and answering codebase questions. State thoroughness in the prompt: "quick" for a targeted lookup, "medium" for checking likely related locations, or "very thorough" for exhaustive sweeps across locations and naming conventions',
|
|
28
|
+
description: 'Fast read-only agent for finding files, searching code, and answering codebase questions. Can inspect git history (log, blame, diff) via read-only bash. State thoroughness in the prompt: "quick" for a targeted lookup, "medium" for checking likely related locations, or "very thorough" for exhaustive sweeps across locations and naming conventions',
|
|
29
29
|
tools: [...EXPLORER_TOOLS],
|
|
30
30
|
systemPrompt: [
|
|
31
31
|
"You are a fast read-only exploration agent; return findings as quickly as possible.",
|
|
32
32
|
"Explore the delegated question without modifying files.",
|
|
33
33
|
"Use read and search tools to gather exact evidence, batching independent searches and reads instead of running them one at a time.",
|
|
34
|
+
"bash is for read-only inspection only: git log/diff/blame/show/status, ls, wc, head, tail, cat, and similar.",
|
|
35
|
+
"Never run anything that modifies state: no file creation or deletion, no redirect (>, >>) or heredoc writes, no temp files, no git commands that write (add, commit, checkout, restore, stash, clean), no installs, no network access.",
|
|
34
36
|
"Match the depth the caller requested: quick targets the direct question, medium checks likely related locations, and very thorough sweeps multiple locations and naming conventions.",
|
|
35
37
|
"Return concise findings with precise paths, symbols, relationships, and unresolved uncertainties.",
|
|
36
38
|
].join("\n"),
|
|
37
39
|
source: "builtin",
|
|
38
40
|
filePath: "<builtin:explorer>",
|
|
39
41
|
backend: "sdk",
|
|
42
|
+
omitContextFiles: true,
|
|
40
43
|
},
|
|
41
44
|
];
|
|
42
45
|
function isDirectory(path) {
|
|
@@ -187,21 +190,24 @@ export function subagentToolDescription(discovery) {
|
|
|
187
190
|
agentListLength += lineLength;
|
|
188
191
|
}
|
|
189
192
|
return [
|
|
190
|
-
|
|
193
|
+
`Delegate bounded work to isolated one-shot subagents. Delegation keeps intermediate tool output (file dumps, search results) out of your context: you receive only the final report. Choose exactly one mode: prompt for one task, or tasks for independent parallel work (up to ${MAX_TASKS} per call; ${MAX_CONCURRENCY} run concurrently, the rest queue). For sequential work, call this tool again with the previous result folded into the next briefing.`,
|
|
191
194
|
"",
|
|
192
195
|
"Available agent profiles:",
|
|
193
196
|
...agentLines,
|
|
194
197
|
"",
|
|
195
198
|
"When not to delegate:",
|
|
196
199
|
"- Read a known file directly with read, or search for a known symbol directly with grep.",
|
|
200
|
+
"- Prefer direct tools when a directed lookup answers the question; delegate when the investigation will clearly take more than ~3 searches or would flood your context with intermediate output.",
|
|
197
201
|
"- Do not delegate a trivial task when the coordination overhead exceeds the work.",
|
|
198
202
|
"",
|
|
199
203
|
"Writing the briefing:",
|
|
200
204
|
"- Brief the worker like a capable colleague entering the project now: include the objective, relevant context, exact paths or symbols already known, constraints, and expected output.",
|
|
201
205
|
"- Never delegate understanding with vague instructions such as 'fix this based on your findings'; state what must be investigated or changed and whether the worker should research, implement, or review.",
|
|
202
|
-
"-
|
|
206
|
+
"- Lookups: hand over the exact command or file. Investigations: hand over the question — prescribed steps become dead weight when the premise is wrong.",
|
|
207
|
+
'- If you need a short answer, say so (e.g. "report in under 200 words"). Workers cannot see the parent conversation or ask the end user questions.',
|
|
208
|
+
'- Example briefing (explorer): "Quick: which commit introduced the retry loop in src/net/client.ts? Use git log/blame; report the hash and a one-line summary."',
|
|
203
209
|
"",
|
|
204
|
-
"
|
|
210
|
+
"The subagent's report is not shown to the user. Interpret it and relay the important findings, changes, verification, and unresolved risks in your own reply.",
|
|
205
211
|
].join("\n");
|
|
206
212
|
}
|
|
207
213
|
//# sourceMappingURL=agents.js.map
|