@demicodes/coding-agent 0.1.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.
- package/LICENSE +201 -0
- package/README.md +15 -0
- package/dist/index.d.mts +28 -0
- package/dist/index.mjs +803 -0
- package/package.json +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# @demicodes/coding-agent
|
|
2
|
+
|
|
3
|
+
A ready-made coding-agent harness for Demi: the system prompt, registered commands
|
|
4
|
+
(an `editor` for file edits, plus shell control), and reference resolution, wired
|
|
5
|
+
to a `Host`. Drop it into an `AgentServer`.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createCodingAgentHarness } from '@demicodes/coding-agent'
|
|
9
|
+
import { LocalHost } from '@demicodes/host-local'
|
|
10
|
+
|
|
11
|
+
const harness = createCodingAgentHarness({ host: new LocalHost(process.cwd()) })
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
See the [Quickstart](../../README.md#quickstart). Part of [Demi](../../README.md).
|
|
15
|
+
Apache-2.0.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { CommandRegistry, CommandSpec, Host } from "@demicodes/shell";
|
|
2
|
+
import { AgentHarness, AgentReferenceResolveContext } from "@demicodes/agent";
|
|
3
|
+
import { UserContentBlock } from "@demicodes/core";
|
|
4
|
+
|
|
5
|
+
//#region src/coding-harness.d.ts
|
|
6
|
+
type CodingState = Record<string, never>;
|
|
7
|
+
interface CodingAgentHarnessOptions {
|
|
8
|
+
host: Host;
|
|
9
|
+
referenceHost?: Host;
|
|
10
|
+
commands?: CommandSpec[];
|
|
11
|
+
}
|
|
12
|
+
interface CodingCommandRegistryOptions {
|
|
13
|
+
editorHost?: Host;
|
|
14
|
+
commands?: CommandSpec[];
|
|
15
|
+
}
|
|
16
|
+
declare function createCodingCommandRegistry(options?: CodingCommandRegistryOptions): CommandRegistry;
|
|
17
|
+
declare function createCodingAgentHarness(options: CodingAgentHarnessOptions): AgentHarness<CodingState>;
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/editor-command.d.ts
|
|
20
|
+
declare function createEditorCommand(host: Host): CommandSpec;
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/reference-resolver.d.ts
|
|
23
|
+
declare function createFileReferenceResolver<State>(host: Host): (ctx: AgentReferenceResolveContext<State>, content: UserContentBlock[]) => Promise<UserContentBlock[]>;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/todo-command.d.ts
|
|
26
|
+
declare function createTodoCommand(): CommandSpec;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { CodingAgentHarnessOptions, CodingCommandRegistryOptions, CodingState, createCodingAgentHarness, createCodingCommandRegistry, createEditorCommand, createFileReferenceResolver, createTodoCommand };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,803 @@
|
|
|
1
|
+
import { CommandRegistry } from "@demicodes/shell";
|
|
2
|
+
import { asError, decodeUtf8, dirnamePath, encodeUtf8, errorMessage } from "@demicodes/utils";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region src/editor-command.ts
|
|
5
|
+
function createEditorCommand(host) {
|
|
6
|
+
return {
|
|
7
|
+
name: "editor",
|
|
8
|
+
summary: "Create, edit, and patch files.",
|
|
9
|
+
subcommands: [
|
|
10
|
+
{
|
|
11
|
+
name: "create",
|
|
12
|
+
summary: "Create a new file. Fails if the file exists.",
|
|
13
|
+
effects: "modifies files by creating a new file; does not modify command storage",
|
|
14
|
+
successOutput: "writes \"Created <path>\" to stdout",
|
|
15
|
+
failureOutput: "writes the reason to stderr and exits non-zero without overwriting existing files",
|
|
16
|
+
input: {
|
|
17
|
+
path: z.string().describe("Target file path"),
|
|
18
|
+
content: z.string().describe("File content, passed via stdin/heredoc")
|
|
19
|
+
},
|
|
20
|
+
positionals: ["path"],
|
|
21
|
+
stdinField: "content",
|
|
22
|
+
examples: ["editor create src/foo.ts <<'EOF'\nexport const foo = 1\nEOF", "editor create README.md <<'EOF'\n# Project\nEOF"],
|
|
23
|
+
run: async ({ parsed, cwd, io }) => {
|
|
24
|
+
const path = String(parsed.values.path);
|
|
25
|
+
const content = String(parsed.values.content);
|
|
26
|
+
const pathError = pathValidationError$1(path);
|
|
27
|
+
if (pathError) {
|
|
28
|
+
await io.stderr(`${pathError}\n`);
|
|
29
|
+
return { exitCode: 1 };
|
|
30
|
+
}
|
|
31
|
+
if (await exists(host, cwd, path)) {
|
|
32
|
+
await io.stderr(`File already exists: ${path}\n`);
|
|
33
|
+
return { exitCode: 1 };
|
|
34
|
+
}
|
|
35
|
+
const parent = dirnamePath(path);
|
|
36
|
+
if (parent !== ".") {
|
|
37
|
+
const made = await mkdirPath(host, cwd, parent);
|
|
38
|
+
if (made.exitCode !== 0) {
|
|
39
|
+
await io.stderr(made.stderr);
|
|
40
|
+
return { exitCode: made.exitCode };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const write = await writeFile(host, cwd, path, content);
|
|
44
|
+
if (write.exitCode !== 0) {
|
|
45
|
+
await io.stderr(write.stderr);
|
|
46
|
+
return { exitCode: write.exitCode };
|
|
47
|
+
}
|
|
48
|
+
await io.stdout(`Created ${path}\n`);
|
|
49
|
+
return {
|
|
50
|
+
exitCode: 0,
|
|
51
|
+
metadata: editorDiffMetadata([fileDiffMetadata("create", null, path, "", content)])
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: "edit",
|
|
57
|
+
summary: "Replace exact text in an existing file.",
|
|
58
|
+
effects: "modifies one existing file; does not modify command storage",
|
|
59
|
+
successOutput: "writes \"Edited <path>\" to stdout",
|
|
60
|
+
failureOutput: "writes no-match, ambiguous-match, or write errors to stderr and exits non-zero without partial writes",
|
|
61
|
+
input: {
|
|
62
|
+
path: z.string().describe("Target file path"),
|
|
63
|
+
old: z.string().describe("Exact text to replace"),
|
|
64
|
+
new: z.string().describe("Replacement text"),
|
|
65
|
+
occurrence: z.number().int().positive().optional().describe("1-based occurrence to replace"),
|
|
66
|
+
context: z.number().int().positive().optional().describe("Line number used to choose nearest occurrence")
|
|
67
|
+
},
|
|
68
|
+
positionals: ["path"],
|
|
69
|
+
examples: ["editor edit src/foo.ts --old foo --new bar", "editor edit src/foo.ts --old \"old text\" --new \"new text\" --occurrence 2"],
|
|
70
|
+
run: async ({ parsed, cwd, io }) => {
|
|
71
|
+
const path = String(parsed.values.path);
|
|
72
|
+
const read = await readFile(host, cwd, path);
|
|
73
|
+
if (read.exitCode !== 0) {
|
|
74
|
+
await io.stderr(read.stderr);
|
|
75
|
+
return { exitCode: read.exitCode };
|
|
76
|
+
}
|
|
77
|
+
const oldText = String(parsed.values.old);
|
|
78
|
+
const newText = String(parsed.values.new);
|
|
79
|
+
if (oldText.length === 0) {
|
|
80
|
+
await io.stderr("Old text must not be empty\n");
|
|
81
|
+
return { exitCode: 1 };
|
|
82
|
+
}
|
|
83
|
+
const matches = findMatches(read.stdout, oldText);
|
|
84
|
+
if (matches.length === 0) {
|
|
85
|
+
await io.stderr(`No match found in ${path}\n`);
|
|
86
|
+
return { exitCode: 1 };
|
|
87
|
+
}
|
|
88
|
+
const selection = chooseMatch(matches, parsed.values.occurrence, parsed.values.context);
|
|
89
|
+
if (!selection.match) {
|
|
90
|
+
await io.stderr(`${selection.reason} in ${path}: ${formatMatches(matches)}\n`);
|
|
91
|
+
return { exitCode: 1 };
|
|
92
|
+
}
|
|
93
|
+
const match = selection.match;
|
|
94
|
+
const content = `${read.stdout.slice(0, match.index)}${newText}${read.stdout.slice(match.index + oldText.length)}`;
|
|
95
|
+
const write = await writeFile(host, cwd, path, content);
|
|
96
|
+
if (write.exitCode !== 0) {
|
|
97
|
+
await io.stderr(write.stderr);
|
|
98
|
+
return { exitCode: write.exitCode };
|
|
99
|
+
}
|
|
100
|
+
await io.stdout(`Edited ${path}\n`);
|
|
101
|
+
return {
|
|
102
|
+
exitCode: 0,
|
|
103
|
+
metadata: editorDiffMetadata([fileDiffMetadata("edit", path, path, read.stdout, content)])
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
name: "patch",
|
|
109
|
+
summary: "Apply a unified diff patch to one or more files.",
|
|
110
|
+
effects: "modifies files described by the patch; validates all patch operations before writing",
|
|
111
|
+
successOutput: "writes \"Patched <n> file(s)\" to stdout",
|
|
112
|
+
failureOutput: "writes parse, validation, or write errors to stderr and exits non-zero after rolling back partial writes when possible",
|
|
113
|
+
input: { patch: z.string().describe("Unified diff content, passed via stdin/heredoc") },
|
|
114
|
+
stdinField: "patch",
|
|
115
|
+
examples: ["editor patch <<'PATCH'\n--- a/src/foo.ts\n+++ b/src/foo.ts\n@@ -1 +1 @@\n-old\n+new\nPATCH", "editor patch <<'PATCH'\n--- /dev/null\n+++ b/src/new.ts\n@@ -0,0 +1 @@\n+export const created = true\nPATCH"],
|
|
116
|
+
run: async ({ parsed, cwd, io }) => {
|
|
117
|
+
let patches;
|
|
118
|
+
let operations;
|
|
119
|
+
try {
|
|
120
|
+
patches = parseUnifiedDiff(String(parsed.values.patch));
|
|
121
|
+
operations = await planPatchOperations(host, cwd, patches);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
await io.stderr(`${asError(error).message}\n`);
|
|
124
|
+
return { exitCode: 1 };
|
|
125
|
+
}
|
|
126
|
+
const applied = await applyPatchOperations(host, cwd, operations);
|
|
127
|
+
if (applied.exitCode !== 0) {
|
|
128
|
+
await io.stderr(applied.stderr);
|
|
129
|
+
return { exitCode: applied.exitCode };
|
|
130
|
+
}
|
|
131
|
+
await io.stdout(`Patched ${patches.length} file(s)\n`);
|
|
132
|
+
return {
|
|
133
|
+
exitCode: 0,
|
|
134
|
+
metadata: editorDiffMetadata(operations.map(operationDiffMetadata))
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
]
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
async function exists(host, cwd, path) {
|
|
142
|
+
if (pathValidationError$1(path)) return false;
|
|
143
|
+
return host.fs.exists(path, { cwd });
|
|
144
|
+
}
|
|
145
|
+
async function readFile(host, cwd, path) {
|
|
146
|
+
const pathError = pathValidationError$1(path);
|
|
147
|
+
if (pathError) return {
|
|
148
|
+
stdout: "",
|
|
149
|
+
stderr: `${pathError}\n`,
|
|
150
|
+
exitCode: 1
|
|
151
|
+
};
|
|
152
|
+
try {
|
|
153
|
+
return {
|
|
154
|
+
stdout: decodeUtf8(await host.fs.readFile(path, { cwd })),
|
|
155
|
+
stderr: "",
|
|
156
|
+
exitCode: 0
|
|
157
|
+
};
|
|
158
|
+
} catch (error) {
|
|
159
|
+
return {
|
|
160
|
+
stdout: "",
|
|
161
|
+
stderr: `${errorMessage(error)}\n`,
|
|
162
|
+
exitCode: 1
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
async function writeFile(host, cwd, path, content) {
|
|
167
|
+
const pathError = pathValidationError$1(path);
|
|
168
|
+
if (pathError) return {
|
|
169
|
+
stdout: "",
|
|
170
|
+
stderr: `${pathError}\n`,
|
|
171
|
+
exitCode: 1
|
|
172
|
+
};
|
|
173
|
+
try {
|
|
174
|
+
await host.fs.writeFile(path, encodeUtf8(content), { cwd });
|
|
175
|
+
return {
|
|
176
|
+
stdout: "",
|
|
177
|
+
stderr: "",
|
|
178
|
+
exitCode: 0
|
|
179
|
+
};
|
|
180
|
+
} catch (error) {
|
|
181
|
+
return {
|
|
182
|
+
stdout: "",
|
|
183
|
+
stderr: `${errorMessage(error)}\n`,
|
|
184
|
+
exitCode: 1
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
async function deleteFile(host, cwd, path) {
|
|
189
|
+
const pathError = pathValidationError$1(path);
|
|
190
|
+
if (pathError) return {
|
|
191
|
+
stdout: "",
|
|
192
|
+
stderr: `${pathError}\n`,
|
|
193
|
+
exitCode: 1
|
|
194
|
+
};
|
|
195
|
+
try {
|
|
196
|
+
await host.fs.rm(path, {
|
|
197
|
+
cwd,
|
|
198
|
+
force: true
|
|
199
|
+
});
|
|
200
|
+
return {
|
|
201
|
+
stdout: "",
|
|
202
|
+
stderr: "",
|
|
203
|
+
exitCode: 0
|
|
204
|
+
};
|
|
205
|
+
} catch (error) {
|
|
206
|
+
return {
|
|
207
|
+
stdout: "",
|
|
208
|
+
stderr: `${errorMessage(error)}\n`,
|
|
209
|
+
exitCode: 1
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
async function mkdirPath(host, cwd, path) {
|
|
214
|
+
const pathError = pathValidationError$1(path);
|
|
215
|
+
if (pathError) return {
|
|
216
|
+
stdout: "",
|
|
217
|
+
stderr: `${pathError}\n`,
|
|
218
|
+
exitCode: 1
|
|
219
|
+
};
|
|
220
|
+
try {
|
|
221
|
+
await host.fs.mkdir(path, {
|
|
222
|
+
cwd,
|
|
223
|
+
recursive: true
|
|
224
|
+
});
|
|
225
|
+
return {
|
|
226
|
+
stdout: "",
|
|
227
|
+
stderr: "",
|
|
228
|
+
exitCode: 0
|
|
229
|
+
};
|
|
230
|
+
} catch (error) {
|
|
231
|
+
return {
|
|
232
|
+
stdout: "",
|
|
233
|
+
stderr: `${errorMessage(error)}\n`,
|
|
234
|
+
exitCode: 1
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function findMatches(content, search) {
|
|
239
|
+
const matches = [];
|
|
240
|
+
let index = content.indexOf(search);
|
|
241
|
+
while (index !== -1) {
|
|
242
|
+
matches.push({
|
|
243
|
+
index,
|
|
244
|
+
line: content.slice(0, index).split("\n").length
|
|
245
|
+
});
|
|
246
|
+
index = content.indexOf(search, index + search.length);
|
|
247
|
+
}
|
|
248
|
+
return matches;
|
|
249
|
+
}
|
|
250
|
+
function chooseMatch(matches, occurrence, context) {
|
|
251
|
+
if (typeof occurrence === "number") {
|
|
252
|
+
const match = matches[occurrence - 1] ?? null;
|
|
253
|
+
return {
|
|
254
|
+
match,
|
|
255
|
+
reason: match ? "" : `Occurrence ${occurrence} is out of range`
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
if (typeof context === "number") {
|
|
259
|
+
const ranked = matches.map((match) => ({
|
|
260
|
+
match,
|
|
261
|
+
distance: Math.abs(match.line - context)
|
|
262
|
+
})).sort((a, b) => a.distance - b.distance);
|
|
263
|
+
const nearest = ranked[0];
|
|
264
|
+
if (!nearest) return {
|
|
265
|
+
match: null,
|
|
266
|
+
reason: "No match found"
|
|
267
|
+
};
|
|
268
|
+
return ranked.filter((entry) => entry.distance === nearest.distance).length === 1 ? {
|
|
269
|
+
match: nearest.match,
|
|
270
|
+
reason: ""
|
|
271
|
+
} : {
|
|
272
|
+
match: null,
|
|
273
|
+
reason: `Context line ${context} is ambiguous`
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
return matches.length === 1 ? {
|
|
277
|
+
match: matches[0],
|
|
278
|
+
reason: ""
|
|
279
|
+
} : {
|
|
280
|
+
match: null,
|
|
281
|
+
reason: "Multiple matches"
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
function formatMatches(matches) {
|
|
285
|
+
return matches.map((match, index) => `occurrence ${index + 1} at line ${match.line}`).join(", ");
|
|
286
|
+
}
|
|
287
|
+
async function applyPatchOperations(host, cwd, operations) {
|
|
288
|
+
const rollback = [];
|
|
289
|
+
const fail = async (failure) => {
|
|
290
|
+
const rollbackFailures = [];
|
|
291
|
+
for (let index = rollback.length - 1; index >= 0; index -= 1) {
|
|
292
|
+
const result = await runRollbackAction(host, cwd, rollback[index]);
|
|
293
|
+
if (result.exitCode !== 0) rollbackFailures.push(result);
|
|
294
|
+
}
|
|
295
|
+
return appendRollbackFailures(failure, rollbackFailures);
|
|
296
|
+
};
|
|
297
|
+
for (const operation of operations) {
|
|
298
|
+
if (operation.type === "delete") {
|
|
299
|
+
rollback.push({
|
|
300
|
+
type: "write",
|
|
301
|
+
path: operation.path,
|
|
302
|
+
content: operation.original
|
|
303
|
+
});
|
|
304
|
+
const deleted = await deleteFile(host, cwd, operation.path);
|
|
305
|
+
if (deleted.exitCode !== 0) return fail(deleted);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
const parent = dirnamePath(operation.path);
|
|
309
|
+
if (parent !== ".") {
|
|
310
|
+
const made = await mkdirPath(host, cwd, parent);
|
|
311
|
+
if (made.exitCode !== 0) return fail(made);
|
|
312
|
+
}
|
|
313
|
+
rollback.push(rollbackForWrite(operation));
|
|
314
|
+
const write = await writeFile(host, cwd, operation.path, operation.content);
|
|
315
|
+
if (write.exitCode !== 0) return fail(write);
|
|
316
|
+
if (operation.deletePath) {
|
|
317
|
+
rollback.push({
|
|
318
|
+
type: "write",
|
|
319
|
+
path: operation.deletePath,
|
|
320
|
+
content: operation.original
|
|
321
|
+
});
|
|
322
|
+
const deleted = await deleteFile(host, cwd, operation.deletePath);
|
|
323
|
+
if (deleted.exitCode !== 0) return fail(deleted);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
stdout: "",
|
|
328
|
+
stderr: "",
|
|
329
|
+
exitCode: 0
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
function rollbackForWrite(operation) {
|
|
333
|
+
if (operation.oldPath === operation.path) return {
|
|
334
|
+
type: "write",
|
|
335
|
+
path: operation.path,
|
|
336
|
+
content: operation.original
|
|
337
|
+
};
|
|
338
|
+
return {
|
|
339
|
+
type: "delete",
|
|
340
|
+
path: operation.path
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
async function runRollbackAction(host, cwd, action) {
|
|
344
|
+
if (action.type === "delete") return deleteFile(host, cwd, action.path);
|
|
345
|
+
const parent = dirnamePath(action.path);
|
|
346
|
+
if (parent !== ".") {
|
|
347
|
+
const made = await mkdirPath(host, cwd, parent);
|
|
348
|
+
if (made.exitCode !== 0) return made;
|
|
349
|
+
}
|
|
350
|
+
return writeFile(host, cwd, action.path, action.content);
|
|
351
|
+
}
|
|
352
|
+
function appendRollbackFailures(failure, rollbackFailures) {
|
|
353
|
+
if (rollbackFailures.length === 0) return failure;
|
|
354
|
+
const rollbackStderr = rollbackFailures.map((result) => result.stderr.trim() || `rollback command exited ${result.exitCode}`).join("\n");
|
|
355
|
+
const separator = failure.stderr.length === 0 || failure.stderr.endsWith("\n") ? "" : "\n";
|
|
356
|
+
return {
|
|
357
|
+
...failure,
|
|
358
|
+
stderr: `${failure.stderr}${separator}Rollback failed:\n${rollbackStderr}\n`
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
function parseUnifiedDiff(diff) {
|
|
362
|
+
const lines = diff.split("\n");
|
|
363
|
+
const patches = [];
|
|
364
|
+
let current = null;
|
|
365
|
+
let hunk = null;
|
|
366
|
+
let pendingOldPath;
|
|
367
|
+
for (const line of lines) {
|
|
368
|
+
if (line.startsWith("--- ")) {
|
|
369
|
+
pendingOldPath = parseDiffPath(line.slice(4));
|
|
370
|
+
hunk = null;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (line.startsWith("+++ ")) {
|
|
374
|
+
if (pendingOldPath === void 0) throw new Error("Invalid patch: new file header before old file header");
|
|
375
|
+
current = {
|
|
376
|
+
oldPath: pendingOldPath,
|
|
377
|
+
newPath: parseDiffPath(line.slice(4)),
|
|
378
|
+
hunks: []
|
|
379
|
+
};
|
|
380
|
+
patches.push(current);
|
|
381
|
+
pendingOldPath = void 0;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (line.startsWith("@@ ")) {
|
|
385
|
+
if (!current) throw new Error("Invalid patch: hunk before file header");
|
|
386
|
+
const match = /^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@/.exec(line);
|
|
387
|
+
if (!match) throw new Error(`Invalid patch hunk header: ${line}`);
|
|
388
|
+
hunk = {
|
|
389
|
+
oldStart: Number(match[1]),
|
|
390
|
+
lines: []
|
|
391
|
+
};
|
|
392
|
+
current.hunks.push(hunk);
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
if (!hunk) continue;
|
|
396
|
+
if (line.startsWith(" ")) hunk.lines.push({
|
|
397
|
+
kind: "context",
|
|
398
|
+
text: line.slice(1)
|
|
399
|
+
});
|
|
400
|
+
else if (line.startsWith("-")) hunk.lines.push({
|
|
401
|
+
kind: "remove",
|
|
402
|
+
text: line.slice(1)
|
|
403
|
+
});
|
|
404
|
+
else if (line.startsWith("+")) hunk.lines.push({
|
|
405
|
+
kind: "add",
|
|
406
|
+
text: line.slice(1)
|
|
407
|
+
});
|
|
408
|
+
else if (line === "\") {
|
|
409
|
+
const previous = hunk.lines[hunk.lines.length - 1];
|
|
410
|
+
if (previous) previous.noNewline = true;
|
|
411
|
+
} else if (line !== "") throw new Error(`Invalid patch line: ${line}`);
|
|
412
|
+
}
|
|
413
|
+
if (patches.length === 0) throw new Error("Invalid patch: no files");
|
|
414
|
+
for (const patch of patches) {
|
|
415
|
+
if (!patch.oldPath && !patch.newPath) throw new Error("Invalid patch: both file paths are /dev/null");
|
|
416
|
+
if (patch.hunks.length === 0) throw new Error(`Invalid patch: ${patchDisplayPath(patch)} has no hunks`);
|
|
417
|
+
}
|
|
418
|
+
return patches;
|
|
419
|
+
}
|
|
420
|
+
async function planPatchOperations(host, cwd, patches) {
|
|
421
|
+
const operations = [];
|
|
422
|
+
for (const patch of patches) {
|
|
423
|
+
const targetPath = patch.newPath ?? patch.oldPath;
|
|
424
|
+
if (!targetPath) throw new Error("Invalid patch: missing target path");
|
|
425
|
+
assertValidPath(targetPath);
|
|
426
|
+
const isCreate = patch.oldPath === null;
|
|
427
|
+
const isDelete = patch.newPath === null;
|
|
428
|
+
let original = "";
|
|
429
|
+
if (isCreate) {
|
|
430
|
+
if (await exists(host, cwd, targetPath)) throw new Error(`File already exists: ${targetPath}`);
|
|
431
|
+
} else {
|
|
432
|
+
const oldPath = patch.oldPath;
|
|
433
|
+
if (oldPath === null) throw new Error("Invalid patch: missing old path");
|
|
434
|
+
assertValidPath(oldPath);
|
|
435
|
+
const read = await readFile(host, cwd, oldPath);
|
|
436
|
+
if (read.exitCode !== 0) throw new Error(read.stderr.trim() || `Failed to read ${oldPath}`);
|
|
437
|
+
original = read.stdout;
|
|
438
|
+
}
|
|
439
|
+
if (patch.newPath) assertValidPath(patch.newPath);
|
|
440
|
+
if (patch.oldPath && patch.newPath && patch.oldPath !== patch.newPath && await exists(host, cwd, patch.newPath)) throw new Error(`File already exists: ${patch.newPath}`);
|
|
441
|
+
const applied = applyFilePatch(original, patch);
|
|
442
|
+
if (isDelete) {
|
|
443
|
+
if (applied !== "") throw new Error(`Delete patch leaves content in ${targetPath}`);
|
|
444
|
+
operations.push({
|
|
445
|
+
type: "delete",
|
|
446
|
+
path: targetPath,
|
|
447
|
+
original,
|
|
448
|
+
oldPath: targetPath,
|
|
449
|
+
newPath: null
|
|
450
|
+
});
|
|
451
|
+
} else {
|
|
452
|
+
const deletePath = patch.oldPath && patch.newPath && patch.oldPath !== patch.newPath ? patch.oldPath : void 0;
|
|
453
|
+
operations.push({
|
|
454
|
+
type: "write",
|
|
455
|
+
path: targetPath,
|
|
456
|
+
content: applied,
|
|
457
|
+
original,
|
|
458
|
+
oldPath: patch.oldPath,
|
|
459
|
+
newPath: targetPath,
|
|
460
|
+
deletePath
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
return operations;
|
|
465
|
+
}
|
|
466
|
+
function applyFilePatch(content, patch) {
|
|
467
|
+
const file = splitTextFile(content);
|
|
468
|
+
const lines = file.lines;
|
|
469
|
+
let finalNewline = file.finalNewline;
|
|
470
|
+
let offset = 0;
|
|
471
|
+
for (const hunk of patch.hunks) {
|
|
472
|
+
const index = hunk.oldStart === 0 ? 0 : hunk.oldStart - 1 + offset;
|
|
473
|
+
const oldLines = hunk.lines.filter((line) => line.kind !== "add").map((line) => line.text);
|
|
474
|
+
const newLines = hunk.lines.filter((line) => line.kind !== "remove").map((line) => line.text);
|
|
475
|
+
if (!arraysEqual(lines.slice(index, index + oldLines.length), oldLines)) throw new Error(`Patch does not apply to ${patchDisplayPath(patch)} at line ${hunk.oldStart}`);
|
|
476
|
+
const touchesEof = index + oldLines.length === lines.length;
|
|
477
|
+
lines.splice(index, oldLines.length, ...newLines);
|
|
478
|
+
offset += newLines.length - oldLines.length;
|
|
479
|
+
if (touchesEof) {
|
|
480
|
+
const lastNewLine = [...hunk.lines].reverse().find((line) => line.kind !== "remove");
|
|
481
|
+
if (lastNewLine) finalNewline = !lastNewLine.noNewline;
|
|
482
|
+
else if (lines.length === 0) finalNewline = false;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return joinTextFile(lines, finalNewline);
|
|
486
|
+
}
|
|
487
|
+
function parseDiffPath(rawPath) {
|
|
488
|
+
const path = stripDiffPathMetadata(rawPath);
|
|
489
|
+
if (path === "/dev/null") return null;
|
|
490
|
+
if (path.startsWith("a/") || path.startsWith("b/")) return path.slice(2);
|
|
491
|
+
return path;
|
|
492
|
+
}
|
|
493
|
+
function assertValidPath(path) {
|
|
494
|
+
const error = pathValidationError$1(path);
|
|
495
|
+
if (error) throw new Error(error);
|
|
496
|
+
}
|
|
497
|
+
function pathValidationError$1(path) {
|
|
498
|
+
if (path.includes("\0")) return `Path contains NUL byte: ${path}`;
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
function stripDiffPathMetadata(rawPath) {
|
|
502
|
+
const trimmed = rawPath.trim();
|
|
503
|
+
const tabIndex = trimmed.indexOf(" ");
|
|
504
|
+
if (tabIndex !== -1) return trimmed.slice(0, tabIndex);
|
|
505
|
+
return trimmed.replace(/\s+\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:\s+[+-]\d{4})?)?$/, "");
|
|
506
|
+
}
|
|
507
|
+
function patchDisplayPath(patch) {
|
|
508
|
+
return patch.newPath ?? patch.oldPath ?? "<unknown>";
|
|
509
|
+
}
|
|
510
|
+
function splitTextFile(content) {
|
|
511
|
+
if (content === "") return {
|
|
512
|
+
lines: [],
|
|
513
|
+
finalNewline: false
|
|
514
|
+
};
|
|
515
|
+
const finalNewline = content.endsWith("\n");
|
|
516
|
+
const body = finalNewline ? content.slice(0, -1) : content;
|
|
517
|
+
return {
|
|
518
|
+
lines: body === "" ? [] : body.split("\n"),
|
|
519
|
+
finalNewline
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
function joinTextFile(lines, finalNewline) {
|
|
523
|
+
if (lines.length === 0) return "";
|
|
524
|
+
return `${lines.join("\n")}${finalNewline ? "\n" : ""}`;
|
|
525
|
+
}
|
|
526
|
+
function arraysEqual(left, right) {
|
|
527
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
528
|
+
}
|
|
529
|
+
function editorDiffMetadata(diffs) {
|
|
530
|
+
return {
|
|
531
|
+
type: "editor_file_diffs",
|
|
532
|
+
diffs
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function operationDiffMetadata(operation) {
|
|
536
|
+
if (operation.type === "delete") return fileDiffMetadata("delete", operation.oldPath, null, operation.original, "");
|
|
537
|
+
return fileDiffMetadata("patch", operation.oldPath, operation.newPath, operation.original, operation.content);
|
|
538
|
+
}
|
|
539
|
+
function fileDiffMetadata(action, oldPath, newPath, oldText, newText) {
|
|
540
|
+
const path = newPath ?? oldPath;
|
|
541
|
+
if (!path) throw new Error("Missing diff path");
|
|
542
|
+
return {
|
|
543
|
+
type: "file_diff",
|
|
544
|
+
action,
|
|
545
|
+
path,
|
|
546
|
+
oldPath,
|
|
547
|
+
newPath,
|
|
548
|
+
oldText,
|
|
549
|
+
newText,
|
|
550
|
+
unifiedDiff: unifiedDiff(oldPath, newPath, oldText, newText)
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
function unifiedDiff(oldPath, newPath, oldText, newText) {
|
|
554
|
+
const oldLines = diffLines(oldText);
|
|
555
|
+
const newLines = diffLines(newText);
|
|
556
|
+
return `${[
|
|
557
|
+
`--- ${oldPath === null ? "/dev/null" : `a/${oldPath}`}`,
|
|
558
|
+
`+++ ${newPath === null ? "/dev/null" : `b/${newPath}`}`,
|
|
559
|
+
`@@ -${diffRange(oldLines.length)} +${diffRange(newLines.length)} @@`,
|
|
560
|
+
...oldLines.map((line) => `-${line}`),
|
|
561
|
+
...newLines.map((line) => `+${line}`)
|
|
562
|
+
].join("\n")}\n`;
|
|
563
|
+
}
|
|
564
|
+
function diffLines(text) {
|
|
565
|
+
if (text === "") return [];
|
|
566
|
+
const body = text.endsWith("\n") ? text.slice(0, -1) : text;
|
|
567
|
+
return body === "" ? [] : body.split("\n");
|
|
568
|
+
}
|
|
569
|
+
function diffRange(lineCount) {
|
|
570
|
+
return lineCount === 0 ? "0,0" : `1,${lineCount}`;
|
|
571
|
+
}
|
|
572
|
+
//#endregion
|
|
573
|
+
//#region src/reference-resolver.ts
|
|
574
|
+
function createFileReferenceResolver(host) {
|
|
575
|
+
return async (ctx, content) => {
|
|
576
|
+
const resolved = [];
|
|
577
|
+
for (const block of content) {
|
|
578
|
+
if (block.type !== "reference") {
|
|
579
|
+
resolved.push(block);
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
resolved.push(await resolveFileReference(host, ctx.cwd, block.reference));
|
|
583
|
+
}
|
|
584
|
+
return resolved;
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
async function resolveFileReference(host, cwd, reference) {
|
|
588
|
+
const path = parseFileReference(reference);
|
|
589
|
+
const pathError = pathValidationError(path);
|
|
590
|
+
if (pathError) throw new Error(pathError);
|
|
591
|
+
let stdout;
|
|
592
|
+
try {
|
|
593
|
+
stdout = decodeUtf8(await host.fs.readFile(path, { cwd }));
|
|
594
|
+
} catch (error) {
|
|
595
|
+
throw new Error(`Failed to resolve file reference "${reference}": ${errorMessage(error)}`);
|
|
596
|
+
}
|
|
597
|
+
return {
|
|
598
|
+
type: "text",
|
|
599
|
+
text: `<file path="${path}">\n${stdout}\n</file>`
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
function parseFileReference(reference) {
|
|
603
|
+
const trimmed = reference.trim();
|
|
604
|
+
if (!trimmed) throw new Error("Empty file reference");
|
|
605
|
+
if (trimmed.startsWith("file://") || trimmed.startsWith("file:/")) return decodeFileReferencePath(new URL(trimmed).pathname);
|
|
606
|
+
if (trimmed.startsWith("file:")) return decodeFileReferencePath(trimmed.slice(5));
|
|
607
|
+
return trimmed;
|
|
608
|
+
}
|
|
609
|
+
function decodeFileReferencePath(path) {
|
|
610
|
+
try {
|
|
611
|
+
return decodeURIComponent(path);
|
|
612
|
+
} catch {
|
|
613
|
+
throw new Error(`Invalid file reference URL encoding: ${path}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
function pathValidationError(path) {
|
|
617
|
+
if (path.includes("\0")) return `File reference contains NUL byte: ${path}`;
|
|
618
|
+
return null;
|
|
619
|
+
}
|
|
620
|
+
//#endregion
|
|
621
|
+
//#region src/todo-command.ts
|
|
622
|
+
const TODO_STORAGE_KEY = "todos.json";
|
|
623
|
+
const TodoStatus = z.enum([
|
|
624
|
+
"pending",
|
|
625
|
+
"in_progress",
|
|
626
|
+
"done"
|
|
627
|
+
]);
|
|
628
|
+
const TodoItemSchema = z.object({
|
|
629
|
+
id: z.string(),
|
|
630
|
+
text: z.string(),
|
|
631
|
+
status: TodoStatus
|
|
632
|
+
});
|
|
633
|
+
const TodoListSchema = z.array(TodoItemSchema);
|
|
634
|
+
function createTodoCommand() {
|
|
635
|
+
return {
|
|
636
|
+
name: "todo",
|
|
637
|
+
summary: "Manage an agent-session-scoped task list for coding work.",
|
|
638
|
+
subcommands: [
|
|
639
|
+
{
|
|
640
|
+
name: "list",
|
|
641
|
+
summary: "List todos for the current agent session.",
|
|
642
|
+
effects: "read-only; does not modify files or command storage",
|
|
643
|
+
successOutput: "writes the session todo list as raw text, or JSON matching { todos } when --json is passed",
|
|
644
|
+
failureOutput: "writes storage or validation errors to stderr and exits non-zero",
|
|
645
|
+
output: { json: z.object({ todos: TodoListSchema }) },
|
|
646
|
+
examples: ["todo list", "todo list --json"],
|
|
647
|
+
run: async ({ parsed, io, storage }) => {
|
|
648
|
+
const todos = await readTodos(storage);
|
|
649
|
+
if (parsed.json) await io.stdout(JSON.stringify({ todos }));
|
|
650
|
+
else if (todos.length === 0) await io.stdout("No todos.\n");
|
|
651
|
+
else await io.stdout(`${todos.map(formatTodo).join("\n")}\n`);
|
|
652
|
+
return { exitCode: 0 };
|
|
653
|
+
}
|
|
654
|
+
},
|
|
655
|
+
{
|
|
656
|
+
name: "add",
|
|
657
|
+
summary: "Add a new todo.",
|
|
658
|
+
effects: "modifies agent-session-scoped command storage; does not modify files",
|
|
659
|
+
successOutput: "writes the created todo as raw text, or JSON matching { todo } when --json is passed",
|
|
660
|
+
failureOutput: "writes validation or storage errors to stderr and exits non-zero",
|
|
661
|
+
input: { text: z.string().describe("Todo text") },
|
|
662
|
+
positionals: ["text"],
|
|
663
|
+
output: { json: z.object({ todo: TodoItemSchema }) },
|
|
664
|
+
examples: ["todo add \"Run tests\"", "todo add \"Run tests\" --json"],
|
|
665
|
+
run: async ({ parsed, io, storage }) => {
|
|
666
|
+
const todos = await readTodos(storage);
|
|
667
|
+
const todo = {
|
|
668
|
+
id: nextTodoId(todos),
|
|
669
|
+
text: String(parsed.values.text),
|
|
670
|
+
status: "pending"
|
|
671
|
+
};
|
|
672
|
+
todos.push(todo);
|
|
673
|
+
await writeTodos(storage, todos);
|
|
674
|
+
if (parsed.json) await io.stdout(JSON.stringify({ todo }));
|
|
675
|
+
else await io.stdout(`${formatTodo(todo)}\n`);
|
|
676
|
+
return { exitCode: 0 };
|
|
677
|
+
}
|
|
678
|
+
},
|
|
679
|
+
{
|
|
680
|
+
name: "update",
|
|
681
|
+
summary: "Update todo text or status.",
|
|
682
|
+
effects: "modifies agent-session-scoped command storage; does not modify files",
|
|
683
|
+
successOutput: "writes the updated todo as raw text, or JSON matching { todo } when --json is passed",
|
|
684
|
+
failureOutput: "writes \"Todo not found\" or validation/storage errors to stderr and exits non-zero",
|
|
685
|
+
input: {
|
|
686
|
+
id: z.string().describe("Todo id"),
|
|
687
|
+
text: z.string().optional().describe("Replacement text"),
|
|
688
|
+
status: TodoStatus.optional().describe("Replacement status")
|
|
689
|
+
},
|
|
690
|
+
positionals: ["id"],
|
|
691
|
+
output: { json: z.object({ todo: TodoItemSchema }) },
|
|
692
|
+
examples: ["todo update T1 --text \"Run full test suite\"", "todo update T1 --status in_progress --json"],
|
|
693
|
+
run: async ({ parsed, io, storage }) => {
|
|
694
|
+
const todos = await readTodos(storage);
|
|
695
|
+
const todo = findTodo(todos, String(parsed.values.id));
|
|
696
|
+
if (!todo) {
|
|
697
|
+
await io.stderr(`Todo not found: ${parsed.values.id}\n`);
|
|
698
|
+
return { exitCode: 1 };
|
|
699
|
+
}
|
|
700
|
+
if (parsed.values.text !== void 0) todo.text = String(parsed.values.text);
|
|
701
|
+
if (parsed.values.status !== void 0) todo.status = parsed.values.status;
|
|
702
|
+
await writeTodos(storage, todos);
|
|
703
|
+
if (parsed.json) await io.stdout(JSON.stringify({ todo }));
|
|
704
|
+
else await io.stdout(`${formatTodo(todo)}\n`);
|
|
705
|
+
return { exitCode: 0 };
|
|
706
|
+
}
|
|
707
|
+
},
|
|
708
|
+
{
|
|
709
|
+
name: "done",
|
|
710
|
+
summary: "Mark a todo as done.",
|
|
711
|
+
effects: "modifies agent-session-scoped command storage; does not modify files",
|
|
712
|
+
successOutput: "writes the completed todo as raw text, or JSON matching { todo } when --json is passed",
|
|
713
|
+
failureOutput: "writes \"Todo not found\" or validation/storage errors to stderr and exits non-zero",
|
|
714
|
+
input: { id: z.string().describe("Todo id") },
|
|
715
|
+
positionals: ["id"],
|
|
716
|
+
output: { json: z.object({ todo: TodoItemSchema }) },
|
|
717
|
+
examples: ["todo done T1", "todo done T1 --json"],
|
|
718
|
+
run: async ({ parsed, io, storage }) => {
|
|
719
|
+
const todos = await readTodos(storage);
|
|
720
|
+
const todo = findTodo(todos, String(parsed.values.id));
|
|
721
|
+
if (!todo) {
|
|
722
|
+
await io.stderr(`Todo not found: ${parsed.values.id}\n`);
|
|
723
|
+
return { exitCode: 1 };
|
|
724
|
+
}
|
|
725
|
+
todo.status = "done";
|
|
726
|
+
await writeTodos(storage, todos);
|
|
727
|
+
if (parsed.json) await io.stdout(JSON.stringify({ todo }));
|
|
728
|
+
else await io.stdout(`${formatTodo(todo)}\n`);
|
|
729
|
+
return { exitCode: 0 };
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
]
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
async function readTodos(storage) {
|
|
736
|
+
return TodoListSchema.parse(await storage.readJson(TODO_STORAGE_KEY) ?? []);
|
|
737
|
+
}
|
|
738
|
+
async function writeTodos(storage, todos) {
|
|
739
|
+
await storage.writeJson(TODO_STORAGE_KEY, todos);
|
|
740
|
+
}
|
|
741
|
+
function findTodo(todos, id) {
|
|
742
|
+
return todos.find((todo) => todo.id === id) ?? null;
|
|
743
|
+
}
|
|
744
|
+
function nextTodoId(todos) {
|
|
745
|
+
let max = 0;
|
|
746
|
+
for (const todo of todos) {
|
|
747
|
+
const match = /^T(\d+)$/.exec(todo.id);
|
|
748
|
+
if (match) max = Math.max(max, Number(match[1]));
|
|
749
|
+
}
|
|
750
|
+
return `T${max + 1}`;
|
|
751
|
+
}
|
|
752
|
+
function formatTodo(todo) {
|
|
753
|
+
return `[${todo.status === "done" ? "x" : todo.status === "in_progress" ? "-" : " "}] ${todo.id} ${todo.text}`;
|
|
754
|
+
}
|
|
755
|
+
//#endregion
|
|
756
|
+
//#region src/coding-harness.ts
|
|
757
|
+
function createCodingCommandRegistry(options = {}) {
|
|
758
|
+
const registry = new CommandRegistry();
|
|
759
|
+
const commands = options.commands ?? [...options.editorHost ? [createEditorCommand(options.editorHost)] : [], createTodoCommand()];
|
|
760
|
+
for (const command of commands) registry.register(command);
|
|
761
|
+
return registry;
|
|
762
|
+
}
|
|
763
|
+
function createCodingAgentHarness(options) {
|
|
764
|
+
const commands = options.commands ?? defaultCodingCommands(options.host);
|
|
765
|
+
return {
|
|
766
|
+
name: "coding",
|
|
767
|
+
initialState: () => ({}),
|
|
768
|
+
host: () => options.host,
|
|
769
|
+
commands: () => [...commands],
|
|
770
|
+
systemPrompt: (ctx) => {
|
|
771
|
+
const sections = [
|
|
772
|
+
"You are a coding agent. Use shell session tools to inspect, edit, test, and verify the workspace.",
|
|
773
|
+
"Treat cwd as the task workspace. Create, edit, and verify task files there by default; do not create a separate project directory under /tmp or another absolute path unless the user asks for it or the workspace is unusable.",
|
|
774
|
+
"Prefer registered commands for agent-specific state and audited workflows. Use normal system commands for ordinary shell work.",
|
|
775
|
+
[
|
|
776
|
+
"Shell session rules:",
|
|
777
|
+
"- Use shell_exec for commands. timeoutMs is required and is only an observation window, not a kill deadline; at timeoutMs the command keeps running and a commandId is returned while the turn continues.",
|
|
778
|
+
"- Tool description: concise title for the concrete user-visible state/result to make visible or confirm. Do not describe waiting, pausing, tool mechanics, generic actions, object labels, steps, tool names, ids, internals, or reasons.",
|
|
779
|
+
"- shell_exec returns shellId, commandId, stdout/stderr deltas, and status. Track commandId for all follow-up control.",
|
|
780
|
+
"- If status is running, the command keeps running and the turn continues. Either call shell_status again to check, or call yield to end this turn and be woken later to check with commandId. shell_exec and shell_status never end the turn or schedule a wakeup on their own; only yield does.",
|
|
781
|
+
"- Use shell_status for polling. It is non-blocking and reads new stdout/stderr since the last snapshot unless offsets are provided.",
|
|
782
|
+
"- For dev servers, watch commands, previews, and other long-running processes that you need to observe and stop, run them in the foreground with a short timeoutMs, use shell_status to observe (and yield to wait between checks), and shell_abort by commandId to stop. Avoid starting them with \"&\" and avoid pkill/killall by process name.",
|
|
783
|
+
"- After a long-running process has been verified and stopped, summarize the observed evidence instead of restarting it to demonstrate the same behavior again.",
|
|
784
|
+
"- If a foreground process is running and you need a separate one-off command, such as curl against a dev server, call shell_exec without shellId; keep using the original commandId to status, write to, or abort the long-running process.",
|
|
785
|
+
"- Prefer non-interactive CLI flags for scaffolds and package tools when available.",
|
|
786
|
+
"- For underspecified scaffold requests, choose a reasonable non-interactive default and proceed unless the choice is destructive or impossible.",
|
|
787
|
+
"- Send non-empty stdin with shell_write only when the running command is known to be waiting for specific input; include a newline such as \"Alice\\n\" for line-oriented prompts.",
|
|
788
|
+
"- For interactive stdin, keep the reader inside one foreground system process such as sh -c, node, or python; do not rely on the session script builtin read across turns.",
|
|
789
|
+
"- Use shell_abort only when intentionally stopping a foreground command, and pass commandId."
|
|
790
|
+
].join("\n"),
|
|
791
|
+
"File references attached by the client are expanded before provider calls."
|
|
792
|
+
];
|
|
793
|
+
if (ctx.commandsPrompt.trim()) sections.push(`Registered commands:\n\n${ctx.commandsPrompt}`);
|
|
794
|
+
return sections.join("\n\n");
|
|
795
|
+
},
|
|
796
|
+
resolveReferences: createFileReferenceResolver(options.referenceHost ?? options.host)
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
function defaultCodingCommands(editorHost) {
|
|
800
|
+
return [createEditorCommand(editorHost), createTodoCommand()];
|
|
801
|
+
}
|
|
802
|
+
//#endregion
|
|
803
|
+
export { createCodingAgentHarness, createCodingCommandRegistry, createEditorCommand, createFileReferenceResolver, createTodoCommand };
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@demicodes/coding-agent",
|
|
3
|
+
"description": "Coding-agent harness, commands, and reference resolution for Demi.",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"development": "./src/index.ts",
|
|
10
|
+
"types": "./dist/index.d.mts",
|
|
11
|
+
"import": "./dist/index.mjs"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@demicodes/agent": "workspace:*",
|
|
16
|
+
"@demicodes/core": "workspace:*",
|
|
17
|
+
"@demicodes/shell": "workspace:*",
|
|
18
|
+
"@demicodes/utils": "workspace:*",
|
|
19
|
+
"zod": "^4.0.0"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@demicodes/provider": "workspace:*"
|
|
23
|
+
},
|
|
24
|
+
"license": "Apache-2.0",
|
|
25
|
+
"main": "./dist/index.mjs",
|
|
26
|
+
"module": "./dist/index.mjs",
|
|
27
|
+
"types": "./dist/index.d.mts",
|
|
28
|
+
"files": [
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsdown"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/wspl/demi.git",
|
|
40
|
+
"directory": "packages/coding-agent"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/wspl/demi/tree/main/packages/coding-agent#readme",
|
|
43
|
+
"bugs": "https://github.com/wspl/demi/issues"
|
|
44
|
+
}
|