@polka-codes/cli 0.10.21 → 0.10.23

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.
@@ -1,390 +0,0 @@
1
- // src/tools/gitDiff.ts
2
- import { z } from "zod";
3
-
4
- // src/tools/utils/diffLineNumbers.ts
5
- function parseHunkHeader(header) {
6
- const match = header.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
7
- if (!match) return null;
8
- return {
9
- oldStart: parseInt(match[1], 10),
10
- oldCount: match[2] ? parseInt(match[2], 10) : 1,
11
- newStart: parseInt(match[3], 10),
12
- newCount: match[4] ? parseInt(match[4], 10) : 1,
13
- header
14
- };
15
- }
16
- function annotateDiffWithLineNumbers(diff) {
17
- const lines = diff.split("\n");
18
- const annotatedLines = [];
19
- let currentNewLine = 0;
20
- let currentOldLine = 0;
21
- let inHunk = false;
22
- for (const line of lines) {
23
- if (line.startsWith("@@")) {
24
- const hunk = parseHunkHeader(line);
25
- if (hunk) {
26
- currentOldLine = hunk.oldStart;
27
- currentNewLine = hunk.newStart;
28
- inHunk = true;
29
- }
30
- annotatedLines.push(line);
31
- continue;
32
- }
33
- if (line.startsWith("diff --git") || line.startsWith("index ") || line.startsWith("---") || line.startsWith("+++")) {
34
- annotatedLines.push(line);
35
- inHunk = false;
36
- continue;
37
- }
38
- if (!inHunk) {
39
- annotatedLines.push(line);
40
- continue;
41
- }
42
- if (line.startsWith("+") && !line.startsWith("+++")) {
43
- annotatedLines.push(`${line} [Line ${currentNewLine}]`);
44
- currentNewLine++;
45
- } else if (line.startsWith("-") && !line.startsWith("---")) {
46
- annotatedLines.push(`${line} [Line ${currentOldLine} removed]`);
47
- currentOldLine++;
48
- } else if (line.startsWith(" ")) {
49
- annotatedLines.push(line);
50
- currentOldLine++;
51
- currentNewLine++;
52
- } else {
53
- annotatedLines.push(line);
54
- }
55
- }
56
- return annotatedLines.join("\n");
57
- }
58
-
59
- // src/tools/gitDiff.ts
60
- var toolInfo = {
61
- name: "git_diff",
62
- description: "Get the git diff for the current repository. Can be used to get staged changes, unstaged changes, or changes between commits. By default, it returns unstaged changes.",
63
- parameters: z.object({
64
- staged: z.preprocess((val) => {
65
- if (typeof val === "string") {
66
- const lower = val.toLowerCase();
67
- if (lower === "false") return false;
68
- if (lower === "true") return true;
69
- }
70
- return val;
71
- }, z.boolean().optional().default(false)).describe("Get staged changes instead of unstaged changes."),
72
- commitRange: z.string().optional().describe('The commit range to get the diff for (e.g., "main...HEAD").'),
73
- file: z.string().describe("Get the diff for a specific file."),
74
- contextLines: z.coerce.number().optional().default(5).describe("Number of context lines to include around changes."),
75
- includeLineNumbers: z.preprocess((val) => {
76
- if (typeof val === "string") {
77
- const lower = val.toLowerCase();
78
- if (lower === "false") return false;
79
- if (lower === "true") return true;
80
- }
81
- return val;
82
- }, z.boolean().optional().default(true)).describe("Annotate the diff with line numbers for additions and deletions.")
83
- })
84
- };
85
- var handler = async (provider, args) => {
86
- if (!provider.executeCommand) {
87
- return {
88
- success: false,
89
- message: {
90
- type: "error-text",
91
- value: "Not possible to execute command. Abort."
92
- }
93
- };
94
- }
95
- const { staged, file, commitRange, contextLines, includeLineNumbers } = toolInfo.parameters.parse(args);
96
- const commandParts = ["git", "diff", "--no-color", `-U${contextLines}`];
97
- if (staged) {
98
- commandParts.push("--staged");
99
- }
100
- if (commitRange) {
101
- commandParts.push(commitRange);
102
- }
103
- if (file) {
104
- const escapedFile = file.replace(/'/g, "'\\''");
105
- commandParts.push("--", `'${escapedFile}'`);
106
- }
107
- const command = commandParts.join(" ");
108
- try {
109
- const result = await provider.executeCommand(command, false);
110
- if (result.exitCode === 0) {
111
- if (!result.stdout.trim()) {
112
- return {
113
- success: true,
114
- message: {
115
- type: "text",
116
- value: "No diff found."
117
- }
118
- };
119
- }
120
- let diffOutput = result.stdout;
121
- if (includeLineNumbers) {
122
- diffOutput = annotateDiffWithLineNumbers(diffOutput);
123
- }
124
- return {
125
- success: true,
126
- message: {
127
- type: "text",
128
- value: `<diff file="${file ?? "all"}">
129
- ${diffOutput}
130
- </diff>`
131
- }
132
- };
133
- }
134
- return {
135
- success: false,
136
- message: {
137
- type: "error-text",
138
- value: `\`${command}\` exited with code ${result.exitCode}:
139
- ${result.stderr}`
140
- }
141
- };
142
- } catch (error) {
143
- return {
144
- success: false,
145
- message: {
146
- type: "error-text",
147
- value: error instanceof Error ? error.message : String(error)
148
- }
149
- };
150
- }
151
- };
152
- var gitDiff_default = {
153
- ...toolInfo,
154
- handler
155
- };
156
-
157
- // src/tools/getTodoItem.ts
158
- import { z as z2 } from "zod";
159
- var toolInfo2 = {
160
- name: "getTodoItem",
161
- description: "Get a to-do item by its ID.",
162
- parameters: z2.object({
163
- id: z2.string().describe("The ID of the to-do item.")
164
- })
165
- };
166
- var handler2 = async (provider, args) => {
167
- if (!provider.getTodoItem) {
168
- return {
169
- success: false,
170
- message: {
171
- type: "error-text",
172
- value: "Not possible to get a to-do item."
173
- }
174
- };
175
- }
176
- const { id } = toolInfo2.parameters.parse(args);
177
- const item = await provider.getTodoItem(id);
178
- return {
179
- success: true,
180
- message: {
181
- type: "json",
182
- value: item ?? null
183
- }
184
- };
185
- };
186
- var getTodoItem_default = {
187
- ...toolInfo2,
188
- handler: handler2
189
- };
190
-
191
- // src/tools/listMemoryTopics.ts
192
- import { z as z3 } from "zod";
193
- var toolInfo3 = {
194
- name: "listMemoryTopics",
195
- description: "Lists all topics in memory. Use this to see what information has been stored and which topics are available to read from.",
196
- parameters: z3.object({})
197
- };
198
- var handler3 = async (provider, _args) => {
199
- const topics = await provider.listMemoryTopics();
200
- if (!topics.length) {
201
- return { success: true, message: { type: "text", value: "No topics found." } };
202
- }
203
- return {
204
- success: true,
205
- message: {
206
- type: "text",
207
- value: `Memory topics:
208
- ${topics.join("\n")}`
209
- }
210
- };
211
- };
212
- var listMemoryTopics_default = {
213
- ...toolInfo3,
214
- handler: handler3
215
- };
216
-
217
- // src/tools/listTodoItems.ts
218
- import { TodoStatus } from "@polka-codes/core";
219
- import { z as z4 } from "zod";
220
- var toolInfo4 = {
221
- name: "listTodoItems",
222
- description: "List all to-do items, sorted by id. If an id is provided, it lists all sub-items for that id. Can be filtered by status.",
223
- parameters: z4.object({
224
- id: z4.string().nullish(),
225
- status: TodoStatus.nullish()
226
- })
227
- };
228
- var handler4 = async (provider, args) => {
229
- if (!provider.listTodoItems) {
230
- return {
231
- success: false,
232
- message: {
233
- type: "error-text",
234
- value: "Not possible to list to-do items."
235
- }
236
- };
237
- }
238
- const { id, status } = toolInfo4.parameters.parse(args);
239
- const items = await provider.listTodoItems(id, status);
240
- return {
241
- success: true,
242
- message: {
243
- type: "json",
244
- value: items
245
- }
246
- };
247
- };
248
- var listTodoItems_default = {
249
- ...toolInfo4,
250
- handler: handler4
251
- };
252
-
253
- // src/tools/readMemory.ts
254
- import { z as z5 } from "zod";
255
- var toolInfo5 = {
256
- name: "readMemory",
257
- description: "Reads content from a memory topic. Use this to retrieve information stored in previous steps. If no topic is specified, reads from the default topic.",
258
- parameters: z5.object({
259
- topic: z5.string().nullish().describe('The topic to read from memory. Defaults to ":default:".')
260
- })
261
- };
262
- var handler5 = async (provider, args) => {
263
- const { topic } = toolInfo5.parameters.parse(args);
264
- const content = await provider.readMemory(topic ?? void 0);
265
- if (content) {
266
- return {
267
- success: true,
268
- message: {
269
- type: "text",
270
- value: `<memory${topic ? ` topic="${topic}"` : ""}>
271
- ${content}
272
- </memory>`
273
- }
274
- };
275
- }
276
- return {
277
- success: true,
278
- message: {
279
- type: "text",
280
- value: `<memory ${topic ? `topic="${topic}"` : ""} isEmpty="true" />`
281
- }
282
- };
283
- };
284
- var readMemory_default = {
285
- ...toolInfo5,
286
- handler: handler5
287
- };
288
-
289
- // src/tools/updateMemory.ts
290
- import { z as z6 } from "zod";
291
- var toolInfo6 = {
292
- name: "updateMemory",
293
- description: 'Appends, replaces, or removes content from a memory topic. Use "append" to add to existing content, "replace" to overwrite entirely, or "remove" to delete a topic. Memory persists across tool calls within a workflow.',
294
- parameters: z6.object({
295
- operation: z6.enum(["append", "replace", "remove"]).describe("The operation to perform."),
296
- topic: z6.string().nullish().describe('The topic to update in memory. Defaults to ":default:".'),
297
- content: z6.string().nullish().describe("The content for append or replace operations. Must be omitted for remove operation.")
298
- }).superRefine((data, ctx) => {
299
- if (data.operation === "append" || data.operation === "replace") {
300
- if (data.content === void 0) {
301
- ctx.addIssue({
302
- code: "custom",
303
- message: 'Content is required for "append" and "replace" operations.',
304
- path: ["content"]
305
- });
306
- }
307
- } else if (data.operation === "remove") {
308
- if (data.content !== void 0) {
309
- ctx.addIssue({
310
- code: "custom",
311
- message: 'Content must not be provided for "remove" operation.',
312
- path: ["content"]
313
- });
314
- }
315
- }
316
- })
317
- };
318
- var handler6 = async (provider, args) => {
319
- if (!provider.updateMemory) {
320
- return {
321
- success: false,
322
- message: {
323
- type: "error-text",
324
- value: "Memory operations are not supported by the current provider."
325
- }
326
- };
327
- }
328
- const params = toolInfo6.parameters.parse(args);
329
- await provider.updateMemory(params.operation, params.topic ?? void 0, params.content ?? void 0);
330
- const topic = params.topic || ":default:";
331
- const messages = {
332
- append: `Content appended to memory topic '${topic}'`,
333
- replace: `Memory topic '${topic}' replaced`,
334
- remove: `Memory topic '${topic}' removed`
335
- };
336
- return {
337
- success: true,
338
- message: {
339
- type: "text",
340
- value: messages[params.operation]
341
- }
342
- };
343
- };
344
- var updateMemory_default = {
345
- ...toolInfo6,
346
- handler: handler6
347
- };
348
-
349
- // src/tools/updateTodoItem.ts
350
- import { UpdateTodoItemInputSchema } from "@polka-codes/core";
351
- var toolInfo7 = {
352
- name: "updateTodoItem",
353
- description: "Add or update a to-do item.",
354
- parameters: UpdateTodoItemInputSchema
355
- };
356
- var handler7 = async (provider, args) => {
357
- if (!provider.updateTodoItem) {
358
- return {
359
- success: false,
360
- message: {
361
- type: "error-text",
362
- value: "Not possible to update a to-do item."
363
- }
364
- };
365
- }
366
- const input = toolInfo7.parameters.parse(args);
367
- const result = await provider.updateTodoItem(input);
368
- return {
369
- success: true,
370
- message: {
371
- type: "json",
372
- value: result
373
- }
374
- };
375
- };
376
- var updateTodoItem_default = {
377
- ...toolInfo7,
378
- handler: handler7
379
- };
380
-
381
- export {
382
- getTodoItem_default,
383
- annotateDiffWithLineNumbers,
384
- gitDiff_default,
385
- listMemoryTopics_default,
386
- listTodoItems_default,
387
- readMemory_default,
388
- updateMemory_default,
389
- updateTodoItem_default
390
- };
@@ -1,277 +0,0 @@
1
- import {
2
- UserCancelledError
3
- } from "./chunk-LLMPMGV3.js";
4
- import {
5
- PlanSchema,
6
- getDefaultContext,
7
- getPlanPrompt,
8
- getPlannerSystemPrompt
9
- } from "./chunk-2LRQ2QH6.js";
10
-
11
- // src/workflows/plan.workflow.ts
12
- import {
13
- agentWorkflow,
14
- askFollowupQuestion,
15
- fetchUrl,
16
- listFiles,
17
- readBinaryFile,
18
- readFile,
19
- searchFiles
20
- } from "@polka-codes/core";
21
- async function createPlan(input, context) {
22
- const { tools, step } = context;
23
- const { task, files, plan: inputPlan, userFeedback, interactive, messages, additionalTools } = input;
24
- const getMessages = async () => {
25
- if (messages) {
26
- return {
27
- messages,
28
- userMessage: [{ role: "user", content: userFeedback ?? task }]
29
- };
30
- } else {
31
- const { context: defaultContext, loadRules } = await getDefaultContext(input.config, "plan");
32
- const memoryContext = await tools.getMemoryContext();
33
- const prompt = `${memoryContext}
34
- ${getPlanPrompt(task, inputPlan)}
35
-
36
- ${defaultContext}`;
37
- const userContent = [{ type: "text", text: prompt }];
38
- if (files) {
39
- for (const file of files) {
40
- if (file.type === "file") {
41
- userContent.push({
42
- type: "file",
43
- mediaType: file.mediaType,
44
- filename: file.filename,
45
- data: { type: "base64", value: file.data }
46
- });
47
- } else if (file.type === "image") {
48
- userContent.push({
49
- type: "image",
50
- mediaType: file.mediaType,
51
- image: { type: "base64", value: file.image }
52
- });
53
- }
54
- }
55
- }
56
- return {
57
- systemPrompt: getPlannerSystemPrompt(loadRules),
58
- userMessage: [{ role: "user", content: userContent }]
59
- };
60
- }
61
- };
62
- const agentTools = [readFile, listFiles, searchFiles, readBinaryFile, fetchUrl];
63
- if (additionalTools?.search) {
64
- agentTools.push(additionalTools.search);
65
- }
66
- if (additionalTools?.mcpTools) {
67
- agentTools.push(...additionalTools.mcpTools);
68
- }
69
- if (interactive) {
70
- agentTools.push(askFollowupQuestion);
71
- }
72
- const inputMessages = await getMessages();
73
- const result = await step("plan", async () => {
74
- return await agentWorkflow(
75
- {
76
- ...inputMessages,
77
- tools: agentTools,
78
- outputSchema: PlanSchema
79
- },
80
- context
81
- );
82
- });
83
- if (result.type === "Exit" && result.object) {
84
- const { plan, question, reason, files: filePaths } = result.object;
85
- if (reason) {
86
- return { reason, messages: result.messages };
87
- }
88
- if (question) {
89
- return { plan: plan || inputPlan, question, messages: result.messages };
90
- }
91
- const outputFiles = [];
92
- if (filePaths) {
93
- for (const path of filePaths) {
94
- const content = await tools.readFile({ path });
95
- if (content) {
96
- outputFiles.push({ path, content });
97
- }
98
- }
99
- }
100
- if (plan) {
101
- try {
102
- const taskSummary = task.split("\n")[0].substring(0, 100);
103
- const topic = `plan:${taskSummary.replace(/[^a-zA-Z0-9_-]+/g, "-").toLowerCase()}`;
104
- const keywords = task.toLowerCase().match(/(?:implement|create|add|fix|refactor|update|improve|optimize|test|document)(?:\s+(\w+))?/g);
105
- const _tags = keywords ? keywords.map((k) => {
106
- const parts = k.split(" ");
107
- if (parts.length > 1) {
108
- return parts.join("-");
109
- }
110
- return k;
111
- }).join(",") : void 0;
112
- await tools.updateMemory({
113
- operation: "replace",
114
- topic,
115
- content: plan
116
- });
117
- context.logger.info(`Plan saved to memory as: ${topic}`);
118
- } catch (error) {
119
- context.logger.warn("Failed to save plan to memory:", error);
120
- }
121
- }
122
- return { plan: plan || void 0, files: outputFiles, messages: result.messages };
123
- }
124
- context.logger.warn("Failed to generate plan.", result);
125
- throw new Error("Failed to generate plan.");
126
- }
127
- var planWorkflow = async (input, context) => {
128
- const { tools, logger, step } = context;
129
- const { fileContent, filePath, mode: inputMode, interactive, additionalTools } = input;
130
- const mode = interactive === false ? "noninteractive" : inputMode ?? "interactive";
131
- let currentTask = input.task;
132
- let plan = fileContent || "";
133
- let files = [];
134
- let userFeedback;
135
- let messages;
136
- let state = "Generating";
137
- let count = 0;
138
- while (state !== "Done") {
139
- state = await step(`plan-iteration-${count++}`, async () => {
140
- switch (state) {
141
- case "Generating": {
142
- if (!currentTask) {
143
- const message = plan ? "How would you like to improve the plan?" : "What is the task you want to plan?";
144
- const defaultTask = plan ? "Review and improve the plan" : void 0;
145
- try {
146
- currentTask = await tools.input({
147
- message,
148
- default: defaultTask
149
- });
150
- } catch (_error) {
151
- return "Done";
152
- }
153
- }
154
- const planResult = await createPlan(
155
- {
156
- task: currentTask,
157
- plan,
158
- userFeedback,
159
- files: input.files,
160
- interactive: mode === "interactive" || mode === "confirm",
161
- messages,
162
- additionalTools,
163
- config: input.config
164
- },
165
- context
166
- );
167
- messages = planResult.messages;
168
- if (planResult.reason) {
169
- logger.info(planResult.reason);
170
- return "Done";
171
- }
172
- if (planResult.question) {
173
- try {
174
- userFeedback = await tools.input({
175
- message: planResult.question.question,
176
- default: planResult.question.defaultAnswer || void 0
177
- });
178
- plan = planResult.plan || plan;
179
- return "Generating";
180
- } catch (error) {
181
- if (error instanceof UserCancelledError) {
182
- throw error;
183
- }
184
- return "Done";
185
- }
186
- }
187
- plan = planResult.plan || "";
188
- files = planResult.files || [];
189
- userFeedback = "";
190
- return "Reviewing";
191
- }
192
- case "Reviewing": {
193
- logger.info("\nGenerated Plan:\n");
194
- logger.info(plan);
195
- if (files?.length > 0) {
196
- logger.info("\nFiles:");
197
- for (const file of files) {
198
- logger.info(`- ${file.path}`);
199
- }
200
- }
201
- if (mode === "noninteractive") {
202
- return "Done";
203
- }
204
- if (mode === "confirm") {
205
- try {
206
- userFeedback = await tools.input({
207
- message: "Do you approve this plan and want to proceed with implementation? (leave blank to approve, or enter feedback)"
208
- });
209
- if (userFeedback === "") {
210
- return "Done";
211
- } else {
212
- return "Generating";
213
- }
214
- } catch (error) {
215
- if (error instanceof UserCancelledError) {
216
- throw error;
217
- }
218
- userFeedback = "";
219
- return "Reviewing";
220
- }
221
- }
222
- const choices = [
223
- { name: "Save Plan", value: "save" },
224
- { name: "Provide Feedback", value: "feedback" },
225
- { name: "Regenerate Plan", value: "regenerate" },
226
- { name: "Exit", value: "exit" }
227
- ];
228
- const choice = await tools.select({
229
- message: "What do you want to do?",
230
- choices
231
- });
232
- switch (choice) {
233
- case "save": {
234
- const defaultPath = `.plans/plan-${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}.md`;
235
- const savePath = filePath || await tools.input({
236
- message: "Where do you want to save the plan?",
237
- default: defaultPath
238
- });
239
- await tools.writeToFile({ path: savePath, content: plan });
240
- logger.info(`Plan saved to ${savePath}`);
241
- return "Done";
242
- }
243
- case "feedback": {
244
- try {
245
- userFeedback = await tools.input({
246
- message: "What changes do you want to make?"
247
- });
248
- return "Generating";
249
- } catch (_error) {
250
- userFeedback = "";
251
- return "Reviewing";
252
- }
253
- }
254
- case "regenerate": {
255
- plan = "";
256
- userFeedback = "";
257
- messages = void 0;
258
- return "Generating";
259
- }
260
- case "exit": {
261
- return "Done";
262
- }
263
- default:
264
- throw new Error(`Invalid mode: ${mode}`);
265
- }
266
- }
267
- default:
268
- throw new Error(`Invalid state: ${state}`);
269
- }
270
- });
271
- }
272
- return { plan, files };
273
- };
274
-
275
- export {
276
- planWorkflow
277
- };