codeply-cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/THIRD_PARTY_NOTICES.md +63 -0
  2. package/bin/codeply.js +562 -370
  3. package/lib/agent.mjs +1627 -160
  4. package/lib/ai.js +1107 -387
  5. package/lib/apply-limit.js +33 -51
  6. package/lib/apply-patch.js +217 -0
  7. package/lib/arity-table.json +138 -0
  8. package/lib/arity.js +70 -0
  9. package/lib/auth.js +118 -112
  10. package/lib/commands.js +103 -0
  11. package/lib/config.js +392 -136
  12. package/lib/design-library/artifact-template.html +500 -0
  13. package/lib/design-library/assemble-artifact.mjs +21 -0
  14. package/lib/design-library/build.mjs +226 -0
  15. package/lib/design-library/cleanup.mjs +45 -0
  16. package/lib/design-library/index.json +22380 -0
  17. package/lib/design-library/make-table-data.mjs +39 -0
  18. package/lib/design-library/query.mjs +104 -0
  19. package/lib/diagnostics.js +192 -0
  20. package/lib/edit-engine.js +171 -14
  21. package/lib/github-agent.mjs +290 -0
  22. package/lib/history.js +75 -0
  23. package/lib/mcp.js +258 -0
  24. package/lib/native-tools.mjs +189 -0
  25. package/lib/oauth-connectors.js +478 -0
  26. package/lib/permissions.js +109 -0
  27. package/lib/plugins.js +353 -0
  28. package/lib/render-md.mjs +617 -617
  29. package/lib/server.mjs +457 -0
  30. package/lib/session-db.js +220 -0
  31. package/lib/share.js +168 -0
  32. package/lib/skills.js +80 -22
  33. package/lib/snapshot.js +146 -0
  34. package/lib/subagents.js +164 -0
  35. package/lib/terminal-hints.js +154 -0
  36. package/lib/textarea.mjs +258 -258
  37. package/lib/tools.mjs +1658 -79
  38. package/lib/tui.js +7 -7
  39. package/lib/tui.mjs +1086 -992
  40. package/lib/typecheck-worker.js +147 -0
  41. package/lib/web-tools.js +158 -0
  42. package/package.json +4 -3
  43. package/skills/premium-web-design/SKILL.md +154 -0
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Native function calling as a transport.
3
+ *
4
+ * Inside the engine everything stays in one format: the model's actions are
5
+ * <codeply:name> blocks in its reply, and results come back as
6
+ * "[tool result: name]" user messages. Every guard in agent.mjs (claim audit,
7
+ * stuck detection, verification gates, batching) works on that format.
8
+ *
9
+ * For models with real function calling this module translates at the edge:
10
+ * - toNativeMessages(): engine history -> OpenAI-shaped history
11
+ * (assistant.tool_calls + role "tool" results), which ai.js sends as is to
12
+ * OpenAI-compatible APIs and converts for Anthropic and Ollama.
13
+ * - toolCallsToTags(): the model's tool calls -> <codeply:...> blocks, so
14
+ * the rest of the loop sees exactly what it would have seen in text mode.
15
+ * Structured arguments mean no tag-format mistakes, and the model uses the
16
+ * calling convention it was trained on.
17
+ */
18
+
19
+ // What the model is told about each action. Parameters not listed as
20
+ // required are optional. Descriptions stay short: the system prompt's RULES
21
+ // section carries the detailed guidance.
22
+ export const TOOL_DOCS = {
23
+ todo: { d: 'Replace your task checklist for a multi-step task. Send the whole list every time.', req: ['items'], p: { items: 'One task per line: "[ ] pending", "[>] in progress" (only one), "[x] done" (only after a tool confirmed it), "[-] dropped".' } },
24
+ ask_user: { d: 'Ask the user a multiple-choice question when a real decision is theirs to make and cannot be inferred from the project.', req: ['question'], p: { question: 'The question, one sentence.', options: 'Up to 5 short answers, one per line, recommended first.' } },
25
+ list_dir: { d: 'List a folder.', req: [], p: { path: 'Folder, relative to the project root. Default ".".' } },
26
+ read_file: { d: 'Read a text file with line numbers.', req: ['path'], p: { path: 'File path.', offset: '0-based line to start at.', limit: 'Max lines (up to 600).' } },
27
+ write_file: { d: 'Create a file or fully rewrite one. For changes to an existing file prefer edit_file.', req: ['path', 'content'], p: { path: 'File path.', content: 'The complete file content, verbatim.' } },
28
+ edit_file: { d: 'Replace one exact block of an existing file.', req: ['path', 'search', 'replace'], p: { path: 'File path.', search: 'Existing text copied exactly from a read (no line-number prefixes), just enough to be unique.', replace: 'The replacement text.', all: '"true" to replace every occurrence (renames).' } },
29
+ search: { d: 'Regex search across project files, or find files by name when only glob is given.', req: [], p: { pattern: 'Case-insensitive regex.', glob: 'Limit to paths like "**/*.ts", or alone to find files by name.', path: 'Folder or single file to search in.', context: 'Lines of surrounding code per hit (0-5).', files_only: '"true" to list matching files with hit counts.' } },
30
+ run: { d: 'Run a shell command in the project folder on the user\'s machine.', req: ['command'], p: { command: 'The command line.' } },
31
+ use_skill: { d: 'Load a skill\'s full instructions.', req: ['name'], p: { name: 'Skill name from the SKILLS list.' } },
32
+ list_skills: { d: 'Search the full skill library.', req: ['query'], p: { query: 'One or two words.' } },
33
+ fetch_image: { d: 'Download an image into the project.', req: ['url', 'path'], p: { url: 'Image URL.', path: 'Where to save it, e.g. assets/hero.jpg.' } },
34
+ browser_check: { d: 'Open a page in a real browser and get errors plus a screenshot.', req: ['url'], p: { url: 'file:///absolute/path or http://localhost:port.', wait: 'Extra milliseconds to wait before capturing.', viewport: 'desktop (default), tablet, mobile, or WIDTHxHEIGHT.' } },
35
+ gmail_send: { d: 'Send a real email now (no drafts). Only when the user asked for it.', req: ['to', 'subject', 'body'], p: { to: 'Recipient address.', subject: 'Subject line.', body: 'Plain-text body.' } },
36
+ gmail_search: { d: 'Search the connected Gmail account.', req: ['query'], p: { query: 'Gmail search syntax.' } },
37
+ slack_post_message: { d: 'Post a real Slack message now. Only when the user asked for it.', req: ['channel', 'text'], p: { channel: 'Channel name or id.', text: 'Message text.' } },
38
+ vercel_deploy: { d: 'Deploy a folder to the connected Vercel account (live, real).', req: [], p: { path: 'Folder to deploy. Default ".".' } },
39
+ supabase_create_project: { d: 'Create a new Supabase project (billable, real).', req: ['name'], p: { name: 'Project name.' } },
40
+ supabase_delete_project: { d: 'Permanently delete a Supabase project. Only when the user clearly asked.', req: [], p: { name: 'Project name.', ref: 'Project ref.' } },
41
+ github_create_repo: { d: 'Create a GitHub repo in the connected account and push this folder to it.', req: ['name'], p: { path: 'Folder to push. Default ".".', name: 'Repository name.' } },
42
+ design_reference_search: { d: 'Search the local library of real app screenshots for a kind of screen.', req: ['term'], p: { term: 'What the screen is, e.g. "checkout".', category: 'Optional category filter.' } },
43
+ view_images: { d: 'Look at images (e.g. reference screenshots).', req: ['urls'], p: { urls: 'Comma-separated image URLs.' } },
44
+ supabase_api: { d: 'Call the Supabase Management API.', req: ['method', 'path'], p: { method: 'GET, POST, PATCH, PUT or DELETE.', path: 'Path starting with /v1/.', body: 'JSON body.' } },
45
+ supabase_sql: { d: 'Run SQL on a Supabase project database.', req: ['ref', 'query'], p: { ref: 'Project ref.', query: 'SQL.' } },
46
+ vercel_api: { d: 'Call the Vercel REST API.', req: ['method', 'path'], p: { method: 'HTTP method.', path: 'Path like /v9/projects.', body: 'JSON body.' } },
47
+ web_fetch: { d: 'Fetch a web page or API URL and get its content as readable text.', req: ['url'], p: { url: 'http:// or https:// URL.', format: '"text" (default, HTML converted to readable text), "html" or "raw".' } },
48
+ web_search: { d: 'Search the web for current information (docs, errors, versions, news).', req: ['query'], p: { query: 'The search query.', num: 'Number of results (1-20, default 8).' } },
49
+ apply_patch: { d: 'Change several files at once (add, update, delete, move) with one patch. Use it for multi-file changes; use edit_file for a single block.', req: ['patch'], p: { patch: 'The patch text: "*** Begin Patch", then "*** Add File: path" (lines start with +), "*** Update File: path" (optional "*** Move to: path", "@@ anchor line", then lines starting with " ", "-" or "+"), "*** Delete File: path", and "*** End Patch".' } },
50
+ lsp: { d: 'Code navigation for TypeScript/JavaScript: find the real definition or every reference of a symbol, hover for its type, outline a file, or search symbols.', req: ['operation'], p: { operation: 'definition, references, implementation, hover, documentSymbol or workspaceSymbol.', path: 'File the symbol is in (not needed for workspaceSymbol).', line: '1-based line of the symbol.', character: '1-based column of the symbol (or give symbol instead).', symbol: 'The name on that line, e.g. fetchUser.', query: 'For workspaceSymbol: the name to look for.' } },
51
+ plan_exit: { d: 'Plan mode only. Call after the plan file is written: asks the user whether to switch to Build mode and start implementing.', req: [], p: { path: 'The plan file, e.g. .codeply/plans/add-login.md. Default: the newest plan file.' } },
52
+ plan_enter: { d: 'Build mode only. Ask the user to switch to Plan mode first, for a large or ambiguous task. Use sparingly.', req: [], p: { reason: 'Why planning first would help, one sentence.' } },
53
+ mcp: { d: 'Call a tool on a connected MCP server.', req: ['server', 'tool'], p: { server: 'Server name from MCP SERVERS.', tool: 'Tool name on that server.', args: 'JSON object of the tool\'s arguments.' } },
54
+ };
55
+
56
+ /** OpenAI-style tool definitions for every action in `params` (name -> param list). */
57
+ export function buildToolSchemas(params) {
58
+ return Object.entries(params).map(([name, list]) => {
59
+ const doc = TOOL_DOCS[name] || { d: name.replace(/_/g, ' '), req: [], p: {} };
60
+ const properties = {};
61
+ for (const p of list) properties[p] = { type: 'string', description: doc.p[p] || p };
62
+ return {
63
+ type: 'function',
64
+ function: {
65
+ name,
66
+ description: doc.d,
67
+ parameters: { type: 'object', properties, required: doc.req.filter((r) => list.includes(r)) },
68
+ },
69
+ };
70
+ });
71
+ }
72
+
73
+ /**
74
+ * Engine history -> OpenAI-shaped native history.
75
+ *
76
+ * Each assistant reply with action blocks becomes one assistant message with
77
+ * tool_calls, followed by exactly one "tool" message per call (APIs reject a
78
+ * tool call with no answer). Results are matched to calls in order by name;
79
+ * a call that got no result (skipped by a guard) gets a short stand-in, and
80
+ * any notes that arrived in between go after the tool messages.
81
+ *
82
+ * @param {Array} messages engine transcript
83
+ * @param {Function} parse agent.mjs parseReply
84
+ */
85
+ export function toNativeMessages(messages, parse, mcpToNative = null) {
86
+ // An engine <codeply:mcp> call goes out as the MCP tool's own function.
87
+ const nativeCall = (c) => {
88
+ if (c.name === 'mcp' && mcpToNative) {
89
+ const fn = mcpToNative[`${c.args?.server}/${c.args?.tool}`];
90
+ if (fn) return { name: fn, arguments: String(c.args?.args || '').trim() || '{}' };
91
+ }
92
+ return { name: c.name, arguments: JSON.stringify(c.args || {}) };
93
+ };
94
+ const out = [];
95
+ let seq = 0;
96
+ let i = 0;
97
+ while (i < messages.length) {
98
+ const m = messages[i];
99
+ if (m.role !== 'assistant' || typeof m.content !== 'string' || !m.content.includes('<codeply:')) {
100
+ out.push(m);
101
+ i++;
102
+ continue;
103
+ }
104
+ const { prose, calls } = parse(m.content);
105
+ if (!calls.length) { out.push(m); i++; continue; }
106
+ const withIds = calls.map((c) => ({ ...c, id: `call_${++seq}` }));
107
+ out.push({
108
+ role: 'assistant',
109
+ content: prose || '',
110
+ tool_calls: withIds.map((c) => ({ id: c.id, type: 'function', function: nativeCall(c) })),
111
+ });
112
+ // Collect everything up to the next assistant message.
113
+ const answers = new Map();
114
+ const notes = [];
115
+ let j = i + 1;
116
+ for (; j < messages.length && messages[j].role !== 'assistant'; j++) {
117
+ const r = messages[j];
118
+ const text = typeof r.content === 'string' ? r.content : (r.content.find?.((p) => p.type === 'text')?.text || '');
119
+ const hit = /^\[tool result: ([a-z_]+)\]/.exec(text);
120
+ const target = hit && withIds.find((c) => c.name === hit[1] && !answers.has(c.id));
121
+ if (target) answers.set(target.id, r);
122
+ else notes.push(r);
123
+ }
124
+ const images = [];
125
+ for (const c of withIds) {
126
+ const r = answers.get(c.id);
127
+ if (!r) {
128
+ out.push({ role: 'tool', tool_call_id: c.id, name: c.name, content: '(not run - see the note that follows)' });
129
+ continue;
130
+ }
131
+ if (typeof r.content === 'string') {
132
+ out.push({ role: 'tool', tool_call_id: c.id, name: c.name, content: r.content });
133
+ } else {
134
+ // Tool messages are text-only on most APIs: screenshots ride in a
135
+ // user message right after the tool results.
136
+ out.push({ role: 'tool', tool_call_id: c.id, name: c.name, content: r.content.find((p) => p.type === 'text')?.text || '' });
137
+ images.push(...r.content.filter((p) => p.type === 'image_url'));
138
+ }
139
+ }
140
+ if (images.length) out.push({ role: 'user', content: [{ type: 'text', text: 'Images from the tool results above:' }, ...images] });
141
+ out.push(...notes);
142
+ i = j;
143
+ }
144
+ return out;
145
+ }
146
+
147
+ /**
148
+ * The model's native tool calls -> the <codeply:...> blocks the loop runs.
149
+ * Unknown tools and unparseable arguments are reported back instead of run.
150
+ * @returns {{ text: string, problems: string[] }}
151
+ */
152
+ export function toolCallsToTags(content, toolCalls, params, mcpFromNative = null) {
153
+ const blocks = [];
154
+ const problems = [];
155
+ for (const tc of toolCalls || []) {
156
+ let name = tc.function?.name;
157
+ const mcpTarget = mcpFromNative && mcpFromNative[name];
158
+ if (!name || (!params[name] && !mcpTarget)) { problems.push(`unknown tool "${name}"`); continue; }
159
+ let args;
160
+ try { args = JSON.parse(tc.function.arguments || '{}'); }
161
+ catch { problems.push(`${name}: arguments were not valid JSON`); continue; }
162
+ if (mcpTarget) {
163
+ args = { server: mcpTarget.server, tool: mcpTarget.tool, args: JSON.stringify(args || {}) };
164
+ name = 'mcp';
165
+ }
166
+ const inner = params[name]
167
+ .filter((p) => args[p] !== undefined && args[p] !== null)
168
+ .map((p) => {
169
+ const v = typeof args[p] === 'string' ? args[p] : JSON.stringify(args[p]);
170
+ return `<${p}>\n${v}\n</${p}>`;
171
+ })
172
+ .join('\n');
173
+ blocks.push(`<codeply:${name}>\n${inner}\n</codeply:${name}>`);
174
+ }
175
+ return { text: [String(content || '').trim(), ...blocks].filter(Boolean).join('\n'), problems };
176
+ }
177
+
178
+ // Replaces the tag examples in the system prompt when native tools are on.
179
+ export const NATIVE_FORMAT = `TOOLS
180
+ You act by calling the tools you have been given (native function calling).
181
+ Call a tool, then stop and wait: its result comes back to you. Up to 4 read_file /
182
+ list_dir / search calls may go in one reply and run together; anything that
183
+ changes something (write_file, edit_file, run, ...) goes alone. Before a call,
184
+ write at most one short sentence. When the task is finished, reply with text
185
+ only and no tool call; that ends your turn. In the rules below, "action block"
186
+ means a tool call.`;
187
+
188
+ /** Errors that mean "this model or endpoint does not do function calling". */
189
+ export const TOOLS_UNSUPPORTED = /does not support tools|tools? (?:are|is) not supported|not support(?:ed)? (?:function|tool)|function calling is not|unsupported parameter:? '?tools|unrecognized request argument.*tools|extra inputs are not permitted.*tools|unknown field .?tools|tool_choice.*not supported|no endpoints found that support tool use/i;