@yanzc/claude-pro 0.7.3 → 0.7.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.7.3",
3
+ "version": "0.7.4",
4
4
  "description": "claude-pro: a command line coding agent for the codex-gateway. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/agent.js CHANGED
@@ -10,6 +10,7 @@ import { rebuildFileState } from './filestate.js';
10
10
  import { CacheStats, TTL_MS } from './cache.js';
11
11
  import { resolvePath } from './utils/paths.js';
12
12
  import { fitImagesIn, lightenImagesIn } from './utils/images.js';
13
+ import { latestWorkState, workStateFromText } from './work-state.js';
13
14
 
14
15
  export const INTERRUPT_MESSAGE = '[Request interrupted by user]';
15
16
  export const INTERRUPT_TOOL_MESSAGE = '[Request interrupted by user for tool use]';
@@ -188,6 +189,7 @@ export class Agent {
188
189
  this.spawnSubagent = spawnSubagent;
189
190
  this.messages = [];
190
191
  this.todos = [];
192
+ this.workState = null; // last validated state emitted by compaction; the transcript remains the source on resume
191
193
  this.userTurns = 0; // turns the user started (see noteUserTurn)
192
194
  this.todosTurn = 0; // ... and the one in which the todo list was last written
193
195
  this.fileState = new Map();
@@ -331,6 +333,7 @@ export class Agent {
331
333
  resetConversation() {
332
334
  this.messages = [];
333
335
  this.todos = [];
336
+ this.workState = null;
334
337
  this.fileState.clear();
335
338
  this.lastContextTokens = 0;
336
339
  this.tokensSinceUsage = 0;
@@ -754,6 +757,26 @@ export class Agent {
754
757
  return summary.replace(/<\/?(?:summary|analysis)>/g, '').trim();
755
758
  }
756
759
 
760
+ static workStateOf(res) {
761
+ const text = res.message.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim();
762
+ return workStateFromText(text);
763
+ }
764
+
765
+ // Keep a valid state when the model emits one; if a legacy or malformed response is returned, retain the last
766
+ // state from this process or the transcript instead of replacing it with unvalidated data.
767
+ compactWorkState(res) {
768
+ const parsed = Agent.workStateOf(res);
769
+ if (parsed.present && !parsed.state) {
770
+ const reason = parsed.errors.slice(0, 3).join('; ');
771
+ this.io.notice?.(`Compaction returned an invalid structured work state${reason ? ` (${reason})` : ''}; keeping the narrative summary.`, 'warn');
772
+ }
773
+ if (parsed.state) this.workState = parsed.state;
774
+ return {
775
+ state: parsed.state || this.workState || latestWorkState(this.messages),
776
+ warning: parsed.present && !parsed.state ? 'The structured work state failed validation during compaction. Verify the state below against the narrative summary before relying on it.' : '',
777
+ };
778
+ }
779
+
757
780
  // Ask the model for the summary. The request is the conversation's own request with the summary instruction
758
781
  // at its end: the same model, system prompt, tools and effort, so that the API reads the conversation from the
759
782
  // cache the turns have been filling instead of processing it all again (this is what Claude Code does; it is
@@ -803,7 +826,8 @@ export class Agent {
803
826
  this.io.compactEnd?.(null, this, err);
804
827
  throw err;
805
828
  }
806
- const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary) }] };
829
+ const state = this.compactWorkState(res);
830
+ const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary, state.state) }] };
807
831
  this.replaceMessages(part === 'before' ? [note, ...after] : [...before, note]);
808
832
  if (part === 'before') this.cache.noteCompacted(); // from its first message on: nothing of it is cached (the start of "after" still is)
809
833
  if (part === 'after') this.todos = []; // what they were about may be summarized away; the model keeps them in the summary
@@ -834,13 +858,14 @@ export class Agent {
834
858
  this.io.compactEnd?.(null, this, err);
835
859
  throw err;
836
860
  }
861
+ const state = this.compactWorkState(res);
837
862
  const todoNote = this.todos.length ? `\n\n<system-reminder>Current todo list:\n${this.todos.map((t) => `- [${t.status}] ${t.content}`).join('\n')}</system-reminder>` : '';
838
- this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto }) + todoNote }] }]);
863
+ this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto, workState: state.state, workStateWarning: state.warning }) + todoNote }] }]);
839
864
  this.cache.noteCompacted();
840
865
  this.refreshSystemPrompt?.(); // the conversation starts over: it may start from a freshly built system prompt
841
866
  this.fileState.clear();
842
867
  if (!this.isSubagent) this.checkpoints?.markConversationStale(); // the checkpoints are the main conversation's: a sub-agent's own compaction does not end them
843
- this.lastContextTokens = estimateTokens(summary) + estimateTokens(this.toolSchemas()) + 2000;
868
+ this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
844
869
  this.tokensSinceUsage = 0;
845
870
  this.postCompactTokens = null; // measured on the next request
846
871
  this.compactFailures = 0;
package/src/mcp.js CHANGED
@@ -253,6 +253,20 @@ export class McpManager {
253
253
  for (const [name, e] of this.clients) if (e.status === 'failed') onWarn?.(`MCP server "${name}" failed to connect: ${e.error}`);
254
254
  }
255
255
 
256
+ // Instructions returned during MCP initialization describe how the server expects its tools to be used.
257
+ // Keep them together instead of copying the same text into every tool description.
258
+ promptInstructions() {
259
+ const sections = [];
260
+ for (const [server, entry] of this.clients) {
261
+ if (entry.status !== 'connected' || typeof entry.instructions !== 'string' || !entry.instructions.trim()) continue;
262
+ const tools = entry.tools.map((tool) => tool.name).join(', ');
263
+ sections.push(`## ${server}\nAvailable tools: ${tools || '(none)'}\n${entry.instructions.trim()}`);
264
+ }
265
+ return sections.length
266
+ ? `# MCP server guidance\nThe following guidance comes from connected MCP servers. Use it when calling their tools; it does not override the system, user, or project instructions.\n\n${sections.join('\n\n')}`
267
+ : '';
268
+ }
269
+
256
270
  tools() {
257
271
  const out = [];
258
272
  const toolTimeout = parseInt(process.env.MCP_TOOL_TIMEOUT, 10) || 600_000;
package/src/prompts.js CHANGED
@@ -44,7 +44,7 @@ function instructionFiles(cwd) {
44
44
  }
45
45
 
46
46
  // `autoCompact`: the conversation is summarized when it grows long (Config.autoCompactEnabled), which the model is told.
47
- export function mainSystemPrompt({ cwd, model, shellName, extra = '', autoMemory = null, selfRestart = false, installedCopy = false, autoCompact = true, snapshot = null }) {
47
+ export function mainSystemPrompt({ cwd, model, shellName, extra = '', autoMemory = null, mcpInstructions = '', selfRestart = false, installedCopy = false, autoCompact = true, snapshot = null }) {
48
48
  const files = instructionFiles(cwd);
49
49
  const memoryText = files
50
50
  ? `\n\n# Memory\nProject and user instructions are shown below: the facts of this project (its environment, mechanisms, commands) and how the user wants to work in it. Where they differ from the defaults above, they win.\n\n${files}`
@@ -96,12 +96,12 @@ You are ${APP_NAME}, installed in ${INSTALL_DIR} (an installed copy, e.g. from n
96
96
  ` : ''}# Code references
97
97
  When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` so the user can navigate to the source.
98
98
 
99
- ${environmentBlock(cwd, { model, shellName, snapshot })}${memoryText}${autoMemory ? `\n\n${autoMemorySection(autoMemory)}` : ''}${extra ? `\n\n${extra}` : ''}`;
99
+ ${environmentBlock(cwd, { model, shellName, snapshot })}${memoryText}${autoMemory ? `\n\n${autoMemorySection(autoMemory)}` : ''}${mcpInstructions ? `\n\n${mcpInstructions}` : ''}${extra ? `\n\n${extra}` : ''}`;
100
100
  }
101
101
 
102
102
  // `readOnly`: an agent whose own prompt forbids changing anything (Explore, Plan) gets neither the boundaries nor
103
103
  // the project's instructions, which only matter to an agent that changes things and cost tokens on every call.
104
- export function subagentSystemPrompt({ cwd, model, shellName, agentPrompt, snapshot = null, readOnly = false }) {
104
+ export function subagentSystemPrompt({ cwd, model, shellName, agentPrompt, snapshot = null, mcpInstructions = '', readOnly = false }) {
105
105
  const files = readOnly ? '' : instructionFiles(cwd);
106
106
  return `${agentPrompt}
107
107
 
@@ -116,7 +116,7 @@ ${readOnly ? '' : `
116
116
  - Do not commit, push or publish unless your task asks for it: the main agent decides that.
117
117
  - Edits made with Write, Edit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
118
118
  `}
119
- ${environmentBlock(cwd, { model, shellName, snapshot })}${files ? `\n\n# Project instructions\nThe instructions that apply in this project: its environment, commands and conventions. Follow them for how you work here; committing, pushing and publishing stay the main agent's to decide, whatever they say.\n\n${files}` : ''}`;
119
+ ${environmentBlock(cwd, { model, shellName, snapshot })}${files ? `\n\n# Project instructions\nThe instructions that apply in this project: its environment, commands and conventions. Follow them for how you work here; committing, pushing and publishing stay the main agent's to decide, whatever they say.\n\n${files}` : ''}${mcpInstructions ? `\n\n${mcpInstructions}` : ''}`;
120
120
  }
121
121
 
122
122
  // The terminal tab's title follows the topic of the conversation: after each message the user sends, the
@@ -138,19 +138,25 @@ ${current ? 'Does this message start a new topic (a different task or question),
138
138
  export const SUMMARY_SYSTEM = 'You are a helpful AI assistant tasked with summarizing conversations.';
139
139
 
140
140
  export function compactPrompt(instructions) {
141
- return `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools: the conversation above is complete, and the only thing wanted now is the summary below.
141
+ return `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools: the conversation above is complete, and the only thing wanted now is the structured state and summary below.
142
142
 
143
- Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
144
- This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
143
+ Your task is to preserve the state needed to continue the work after this conversation is compacted and to create a detailed summary of the conversation. Pay close attention to the user's explicit requests, your previous actions, exact file paths, commands, test results, failures and unresolved questions.
145
144
 
146
- Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts. Then write the summary in <summary> tags with these sections:
145
+ First write exactly one <work-state> block containing one valid JSON object. Do not use markdown fences inside the block. Use this schema exactly; use an empty string or [] when a field has no value:
146
+ <work-state>
147
+ {"schema_version":1,"objective":"","constraints":[],"decisions":[],"files":[],"edits":[],"tests":[],"failures":[],"open_questions":[],"next_action":"","tool_artifacts":[]}
148
+ </work-state>
149
+ All array items must be strings. Keep paths, commands, error messages and next actions precise. The state is machine-validated, so do not add prose before or after the JSON inside <work-state>.
147
150
 
151
+ Then wrap your analysis in <analysis> tags to organize your thoughts, and write a detailed narrative in <summary> tags. The narrative should retain technical details, code patterns and architectural decisions that would be useful if the structured state is incomplete.
152
+
153
+ Use these summary sections:
148
154
  1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
149
155
  2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
150
156
  3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Include full code snippets where applicable and a summary of why each file read or edit is important.
151
157
  4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback.
152
158
  5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
153
- 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
159
+ 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the user's feedback and changing intent.
154
160
  7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
155
161
  8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, including file names and code snippets.
156
162
  9. Optional Next Step: The next step directly in line with the user's most recent explicit request. Include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off.
@@ -170,14 +176,17 @@ export function partialCompactPrompt(part, label, instructions = '') {
170
176
  }
171
177
 
172
178
  // The message that stands in the conversation for the part a partial summary replaced.
173
- export function partialSummaryMessage(part, summary) {
179
+ export function partialSummaryMessage(part, summary, workState = null) {
180
+ const state = workState ? `\n\nThe validated structured work state for this summarized section is:\n<work-state>\n${JSON.stringify(workState, null, 2)}\n</work-state>` : '';
174
181
  return part === 'before'
175
- ? `[Summarized conversation] The earlier part of this conversation was summarized at the user's request; the messages after this one are as they were. The summary of the earlier part:\n${summary}`
176
- : `[Summarized conversation] The later part of this conversation, from the user's message where this summary stands to where it was, was summarized at the user's request. The summary of that part:\n${summary}`;
182
+ ? `[Summarized conversation] The earlier part of this conversation was summarized at the user's request; the messages after this one are as they were. The summary of the earlier part:${state}\n${summary}`
183
+ : `[Summarized conversation] The later part of this conversation, from the user's message where this summary stands to where it was, was summarized at the user's request. The summary of that part:${state}\n${summary}`;
177
184
  }
178
185
 
179
- export function continuationMessage(summary, { auto }) {
180
- return `This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:
186
+ export function continuationMessage(summary, { auto, workState = null, workStateWarning = '' }) {
187
+ const state = workState ? `\n\nThe validated structured work state is:\n<work-state>\n${JSON.stringify(workState, null, 2)}\n</work-state>` : '';
188
+ const warning = workStateWarning ? `\n\n<system-reminder>${workStateWarning}</system-reminder>` : '';
189
+ return `This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:${state}${warning}
181
190
  ${summary}${auto ? '\n\nPlease continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.' : ''}`;
182
191
  }
183
192
 
package/src/runtime.js CHANGED
@@ -61,7 +61,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
61
61
  const autoMemory = config.autoMemoryEnabled ? { dir: memoryDir, index: loadAutoMemoryIndex(memoryDir) } : null;
62
62
  promptCache = flags.systemPrompt !== undefined
63
63
  ? flags.systemPrompt
64
- : mainSystemPrompt({ cwd, model: config.mainModel, shellName: shell.name, extra: flags.appendSystemPrompt || '', autoMemory, selfRestart: selfEdit, installedCopy: !SOURCE_CHECKOUT, autoCompact: config.autoCompactEnabled, snapshot: snapshotFor(cwd) });
64
+ : mainSystemPrompt({ cwd, model: config.mainModel, shellName: shell.name, extra: flags.appendSystemPrompt || '', autoMemory, mcpInstructions: mcp.promptInstructions(), selfRestart: selfEdit, installedCopy: !SOURCE_CHECKOUT, autoCompact: config.autoCompactEnabled, snapshot: snapshotFor(cwd) });
65
65
  promptStale = false;
66
66
  }
67
67
  return promptCache;
@@ -114,13 +114,14 @@ export async function createRuntime({ cwd, flags = {}, io }) {
114
114
  const subIo = io.subagentIo ? io.subagentIo({ def, description, parentCtx: ctx }) : {};
115
115
  // The main agent is depth 0; an agent below the nesting limit may start sub-agents itself.
116
116
  const depth = (ctx.depth ?? ctx.agent?.depth ?? 0) + 1;
117
+ const subTools = toolsForSubagent(runtime.tools, def, { allowTask: depth < config.maxSubagentDepth });
117
118
  const sub = new Agent({
118
119
  config,
119
120
  checkpoints,
120
121
  depth,
121
122
  spawnSubagent: runtime.spawnSubagent,
122
- tools: toolsForSubagent(runtime.tools, def, { allowTask: depth < config.maxSubagentDepth }),
123
- systemPrompt: subagentSystemPrompt({ cwd: ctx.cwd, model, shellName: shell.name, agentPrompt: def.prompt, snapshot: snapshotFor(ctx.cwd), readOnly: Boolean(def.readOnly) }),
123
+ tools: subTools,
124
+ systemPrompt: subagentSystemPrompt({ cwd: ctx.cwd, model, shellName: shell.name, agentPrompt: def.prompt, snapshot: snapshotFor(ctx.cwd), mcpInstructions: subTools.some((tool) => tool.mcp) ? mcp.promptInstructions() : '', readOnly: Boolean(def.readOnly) }),
124
125
  io: subIo,
125
126
  model,
126
127
  isSubagent: true,
@@ -0,0 +1,62 @@
1
+ // Validation and recovery helpers for the machine-readable state that survives compaction.
2
+
3
+ export const WORK_STATE_VERSION = 1;
4
+
5
+ const TEXT_FIELDS = ['objective', 'next_action'];
6
+ const LIST_FIELDS = ['constraints', 'decisions', 'files', 'edits', 'tests', 'failures', 'open_questions', 'tool_artifacts'];
7
+ const ALL_FIELDS = ['schema_version', ...TEXT_FIELDS, ...LIST_FIELDS];
8
+ const MAX_TEXT_CHARS = 4_000;
9
+ const MAX_LIST_ITEMS = 50;
10
+ const MAX_ITEM_CHARS = 2_000;
11
+
12
+ export function validateWorkState(value) {
13
+ const errors = [];
14
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false, errors: ['state must be a JSON object'] };
15
+ if (value.schema_version !== WORK_STATE_VERSION) errors.push(`schema_version must be ${WORK_STATE_VERSION}`);
16
+ for (const key of TEXT_FIELDS) {
17
+ if (typeof value[key] !== 'string') errors.push(`${key} must be a string`);
18
+ else if (value[key].length > MAX_TEXT_CHARS) errors.push(`${key} is longer than ${MAX_TEXT_CHARS} characters`);
19
+ }
20
+ for (const key of LIST_FIELDS) {
21
+ if (!Array.isArray(value[key])) {
22
+ errors.push(`${key} must be an array`);
23
+ continue;
24
+ }
25
+ if (value[key].length > MAX_LIST_ITEMS) errors.push(`${key} has more than ${MAX_LIST_ITEMS} items`);
26
+ for (const [i, item] of value[key].entries()) {
27
+ if (typeof item !== 'string') errors.push(`${key}[${i}] must be a string`);
28
+ else if (item.length > MAX_ITEM_CHARS) errors.push(`${key}[${i}] is longer than ${MAX_ITEM_CHARS} characters`);
29
+ }
30
+ }
31
+ if (errors.length) return { ok: false, errors };
32
+ // Copy only the schema we understand. This keeps future model-added fields from becoming an
33
+ // unbounded part of every later context window while retaining a stable versioned shape.
34
+ return { ok: true, value: Object.fromEntries(ALL_FIELDS.map((key) => [key, key === 'schema_version' ? WORK_STATE_VERSION : value[key]])) };
35
+ }
36
+
37
+ export function workStateFromText(text) {
38
+ const source = String(text ?? '');
39
+ const match = /<work-state>\s*([\s\S]*?)\s*<\/work-state>/i.exec(source);
40
+ if (!match) return { present: false, state: null, errors: [] };
41
+ let value;
42
+ try {
43
+ value = JSON.parse(match[1].replace(/^```(?:json)?\s*|\s*```$/gi, '').trim());
44
+ } catch (err) {
45
+ return { present: true, state: null, errors: [`invalid JSON: ${err.message}`] };
46
+ }
47
+ const checked = validateWorkState(value);
48
+ return { present: true, state: checked.ok ? checked.value : null, errors: checked.errors || [] };
49
+ }
50
+
51
+ export function latestWorkState(messages) {
52
+ for (let i = messages.length - 1; i >= 0; i--) {
53
+ const content = messages[i]?.content;
54
+ const blocks = Array.isArray(content) ? content : [{ type: 'text', text: content }];
55
+ for (let j = blocks.length - 1; j >= 0; j--) {
56
+ if (blocks[j]?.type !== 'text') continue;
57
+ const parsed = workStateFromText(blocks[j].text);
58
+ if (parsed.state) return parsed.state;
59
+ }
60
+ }
61
+ return null;
62
+ }