@agimon-ai/po-edit 0.0.0-alpha.7 → 0.0.0-alpha.70
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 +165 -1
- package/README.md +5 -1
- package/dist/apiContracts.cjs +1 -1
- package/dist/apiContracts.cjs.map +1 -1
- package/dist/apiContracts.d.mts +1 -1
- package/dist/apiContracts.mjs +1 -1
- package/dist/apiContracts.mjs.map +1 -1
- package/dist/{editTool--RaZ-yPH.mjs → editTool-DVt2xCNP.mjs} +22 -14
- package/dist/editTool-DVt2xCNP.mjs.map +1 -0
- package/dist/{editTool-BKaEjUdm.cjs → editTool-VO-ySAzl.cjs} +22 -14
- package/dist/editTool-VO-ySAzl.cjs.map +1 -0
- package/dist/extensions/mcp.cjs +26 -14
- package/dist/extensions/mcp.cjs.map +1 -1
- package/dist/extensions/mcp.mjs +26 -14
- package/dist/extensions/mcp.mjs.map +1 -1
- package/dist/extensions/native.mjs +217 -0
- package/dist/extensions/native.mjs.map +1 -0
- package/dist/extensions/server.cjs +20 -6
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.d.mts +2 -2
- package/dist/extensions/server.d.mts.map +1 -1
- package/dist/extensions/server.mjs +19 -5
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +12 -21
- package/dist/extensions/web.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts +4 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +41 -14
- package/dist/editTool--RaZ-yPH.mjs.map +0 -1
- package/dist/editTool-BKaEjUdm.cjs.map +0 -1
package/LICENSE
CHANGED
|
@@ -1,6 +1,170 @@
|
|
|
1
|
+
License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
|
|
2
|
+
"Business Source License" is a trademark of MariaDB Corporation Ab.
|
|
3
|
+
|
|
4
|
+
Parameters
|
|
5
|
+
|
|
6
|
+
Licensor: Agimon Pty Ltd
|
|
7
|
+
Licensed Work: Po, the software in the Po source repository and the
|
|
8
|
+
packages released from it, in each version released by
|
|
9
|
+
the Licensor.
|
|
10
|
+
The Licensed Work is (c) 2026 Agimon Pty Ltd.
|
|
11
|
+
Material identified as third-party in the "Third-party
|
|
12
|
+
components" section at the end of this file or in a
|
|
13
|
+
NOTICE file, and any package or directory whose own
|
|
14
|
+
license file grants a different license, is not part of
|
|
15
|
+
the Licensed Work and remains under its own license.
|
|
16
|
+
Additional Use Grant: You may make production use of the Licensed Work if
|
|
17
|
+
your use is Eligible Use. "Eligible Use" is production use that falls
|
|
18
|
+
within at least one of the following:
|
|
19
|
+
|
|
20
|
+
(a) Personal Use. Use by an individual for their own personal purposes,
|
|
21
|
+
and not on behalf of, or for the benefit of, an employer, client, or
|
|
22
|
+
other Organization. Use by an individual in the course of employment
|
|
23
|
+
or engagement by an Organization is use by that Organization.
|
|
24
|
+
|
|
25
|
+
(b) Small Organization Use. Use by or on behalf of an Organization whose
|
|
26
|
+
Annual Revenue is less than USD 1,000,000.
|
|
27
|
+
|
|
28
|
+
(c) Non-profit, Education and Research Use. Use, regardless of Annual
|
|
29
|
+
Revenue, by (i) an Organization registered or recognized as a
|
|
30
|
+
non-profit or charitable organization under the laws of its
|
|
31
|
+
jurisdiction, for its non-profit purposes; (ii) an accredited school,
|
|
32
|
+
college, or university, for teaching, learning, or academic research;
|
|
33
|
+
or (iii) a publicly funded research institution, for its research.
|
|
34
|
+
|
|
35
|
+
(d) Service Provider Use. Use by a consultant, contractor, agency, or other
|
|
36
|
+
service provider, regardless of its own Annual Revenue, solely to
|
|
37
|
+
build, deploy, host, operate, or support the Licensed Work for a client
|
|
38
|
+
whose own use would be Eligible Use under (a), (b), or (c). A service
|
|
39
|
+
provider's use for its own purposes is Eligible Use only if the service
|
|
40
|
+
provider itself qualifies under (b) or (c).
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Hosted services. Offering the Licensed Work to third parties as a hosted
|
|
44
|
+
or managed service whose primary value is the Licensed Work is Eligible
|
|
45
|
+
Use only if each such third party's own use would be Eligible Use.
|
|
46
|
+
|
|
47
|
+
Definitions. "Organization" means any company, partnership, sole
|
|
48
|
+
proprietorship, trust, association, government body, or other entity, and
|
|
49
|
+
includes an individual acting in a business or professional capacity.
|
|
50
|
+
"Affiliate" means any entity that directly or indirectly controls, is
|
|
51
|
+
controlled by, or is under common control with an Organization, where
|
|
52
|
+
"control" means ownership of more than 50% of the voting interests of an
|
|
53
|
+
entity or the power to direct its management and policies by contract or
|
|
54
|
+
otherwise. "Annual Revenue" means the total gross revenue of an
|
|
55
|
+
Organization and all of its Affiliates combined, from all sources and
|
|
56
|
+
whether or not related to the Licensed Work, for its most recently
|
|
57
|
+
completed fiscal year, or, if it has not completed a fiscal year, for the
|
|
58
|
+
twelve months before the use (or since its formation, if shorter),
|
|
59
|
+
converted into US dollars at the average exchange rate for that period.
|
|
60
|
+
Proceeds of equity or debt financing are not revenue.
|
|
61
|
+
|
|
62
|
+
Threshold. If an Organization stops qualifying under (b), its existing
|
|
63
|
+
production use remains Eligible Use for 90 days after it stops
|
|
64
|
+
qualifying, after which it must obtain a commercial license or stop
|
|
65
|
+
production use. Use that was Eligible Use when it occurred never requires
|
|
66
|
+
a commercial license after the fact.
|
|
67
|
+
Change Date: Four years from the date a version of the Licensed Work
|
|
68
|
+
is first publicly released by the Licensor.
|
|
69
|
+
Change License: Apache License, Version 2.0
|
|
70
|
+
|
|
71
|
+
For information about alternative licensing arrangements for the Licensed
|
|
72
|
+
Work, please visit: https://agimon.ai/licensing
|
|
73
|
+
|
|
74
|
+
Notice
|
|
75
|
+
|
|
76
|
+
The Business Source License (this document, or the "License") is not an Open
|
|
77
|
+
Source license. However, the Licensed Work will eventually be made available
|
|
78
|
+
under an Open Source License, as stated in this License.
|
|
79
|
+
|
|
80
|
+
-----------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
Business Source License 1.1
|
|
83
|
+
|
|
84
|
+
Terms
|
|
85
|
+
|
|
86
|
+
The Licensor hereby grants you the right to copy, modify, create derivative
|
|
87
|
+
works, redistribute, and make non-production use of the Licensed Work. The
|
|
88
|
+
Licensor may make an Additional Use Grant, above, permitting limited
|
|
89
|
+
production use.
|
|
90
|
+
|
|
91
|
+
Effective on the Change Date, or the fourth anniversary of the first publicly
|
|
92
|
+
available distribution of a specific version of the Licensed Work under this
|
|
93
|
+
License, whichever comes first, the Licensor hereby grants you rights under
|
|
94
|
+
the terms of the Change License, and the rights granted in the paragraph
|
|
95
|
+
above terminate.
|
|
96
|
+
|
|
97
|
+
If your use of the Licensed Work does not comply with the requirements
|
|
98
|
+
currently in effect as described in this License, you must purchase a
|
|
99
|
+
commercial license from the Licensor, its affiliated entities, or authorized
|
|
100
|
+
resellers, or you must refrain from using the Licensed Work.
|
|
101
|
+
|
|
102
|
+
All copies of the original and modified Licensed Work, and derivative works
|
|
103
|
+
of the Licensed Work, are subject to this License. This License applies
|
|
104
|
+
separately for each version of the Licensed Work and the Change Date may vary
|
|
105
|
+
for each version of the Licensed Work released by Licensor.
|
|
106
|
+
|
|
107
|
+
You must conspicuously display this License on each original or modified copy
|
|
108
|
+
of the Licensed Work. If you receive the Licensed Work in original or
|
|
109
|
+
modified form from a third party, the terms and conditions set forth in this
|
|
110
|
+
License apply to your use of that work.
|
|
111
|
+
|
|
112
|
+
Any use of the Licensed Work in violation of this License will automatically
|
|
113
|
+
terminate your rights under this License for the current and all other
|
|
114
|
+
versions of the Licensed Work.
|
|
115
|
+
|
|
116
|
+
This License does not grant you any right in any trademark or logo of
|
|
117
|
+
Licensor or its affiliates (provided that you may use a trademark or logo of
|
|
118
|
+
Licensor as expressly required by this License).
|
|
119
|
+
|
|
120
|
+
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
|
|
121
|
+
AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
|
|
122
|
+
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
|
|
123
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
|
|
124
|
+
TITLE.
|
|
125
|
+
|
|
126
|
+
MariaDB hereby grants you permission to use this License’s text to license
|
|
127
|
+
your works, and to refer to it using the trademark “Business Source License”,
|
|
128
|
+
as long as you comply with the Covenants of Licensor below.
|
|
129
|
+
|
|
130
|
+
Covenants of Licensor
|
|
131
|
+
|
|
132
|
+
In consideration of the right to use this License’s text and the “Business
|
|
133
|
+
Source License” name and trademark, Licensor covenants to MariaDB, and to all
|
|
134
|
+
other recipients of the licensed work to be provided by Licensor:
|
|
135
|
+
|
|
136
|
+
1. To specify as the Change License the GPL Version 2.0 or any later version,
|
|
137
|
+
or a license that is compatible with GPL Version 2.0 or a later version,
|
|
138
|
+
where “compatible” means that software provided under the Change License can
|
|
139
|
+
be included in a program with software provided under GPL Version 2.0 or a
|
|
140
|
+
later version. Licensor may specify additional Change Licenses without
|
|
141
|
+
limitation.
|
|
142
|
+
|
|
143
|
+
2. To either: (a) specify an additional grant of rights to use that does not
|
|
144
|
+
impose any additional restriction on the right granted in this License, as
|
|
145
|
+
the Additional Use Grant; or (b) insert the text “None”.
|
|
146
|
+
|
|
147
|
+
3. To specify a Change Date.
|
|
148
|
+
|
|
149
|
+
4. Not to modify this License in any other way.
|
|
150
|
+
|
|
151
|
+
-----------------------------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
Third-party components
|
|
154
|
+
|
|
155
|
+
The following material in this package was written by third parties. It is
|
|
156
|
+
not part of the Licensed Work, is not licensed under the Business Source
|
|
157
|
+
License above, and remains under its own license, reproduced below. Where a
|
|
158
|
+
file combines third-party material with changes by Agimon Pty Ltd, the
|
|
159
|
+
third-party portions remain under their original license and the changes
|
|
160
|
+
are part of the Licensed Work.
|
|
161
|
+
|
|
162
|
+
1. Phi writetool (https://github.com/pulseaiclub/phi/tree/main/internal/tools/writetool)
|
|
163
|
+
Used in: hashline protocol and FNV anchor implementation
|
|
164
|
+
License: MIT
|
|
165
|
+
|
|
1
166
|
MIT License
|
|
2
167
|
|
|
3
|
-
Copyright (c) 2026 Vuong Ngo
|
|
4
168
|
Copyright (c) 2026 pulseaiclub
|
|
5
169
|
|
|
6
170
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
package/README.md
CHANGED
|
@@ -51,6 +51,10 @@ Pass exactly one anchor in each `from` and `to` value, for example `5#abc`. Anch
|
|
|
51
51
|
`>`, `+`, or `-` display prefix are accepted, as are uppercase anchor letters, whitespace around
|
|
52
52
|
the separator, and the legacy `5:abc` separator. Pasted multiline blocks are rejected.
|
|
53
53
|
|
|
54
|
+
Files over 8 MiB are refused before decoding or preparing edits, including reads with a small
|
|
55
|
+
`limit`. Use runner log tools for logs. Factories require an injected `FileSystem` or getter;
|
|
56
|
+
execution functions take a `FileSystem` after the abort signal.
|
|
57
|
+
|
|
54
58
|
## Attribution
|
|
55
59
|
|
|
56
60
|
The hashline protocol and FNV anchor approach are adapted from
|
|
@@ -78,6 +82,6 @@ Maintained by [Agimon](https://agimon.ai/about).
|
|
|
78
82
|
|
|
79
83
|
## License
|
|
80
84
|
|
|
81
|
-
|
|
85
|
+
Business Source License 1.1: free for personal use, organisations under USD 1M revenue, non-profits and education. See [LICENSE](LICENSE) and https://agimon.ai/licensing.
|
|
82
86
|
|
|
83
87
|
The native tool declaration consumes `services/editTool`, and reusable factories and schemas are exposed through flat `src/exports`.
|
package/dist/apiContracts.cjs
CHANGED
|
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
|
|
|
3
3
|
[Symbol.toStringTag]: { value: "Module" }
|
|
4
4
|
});
|
|
5
5
|
//#region src/schemas/apiContracts.ts
|
|
6
|
-
/** This
|
|
6
|
+
/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
|
|
7
7
|
const apiContracts = (0, require("@agimon-ai/po-core/apiContracts").defineApiContract)({
|
|
8
8
|
version: 1,
|
|
9
9
|
http: [],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiContracts.cjs","names":["defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This
|
|
1
|
+
{"version":3,"file":"apiContracts.cjs","names":["defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;;;;AAGA,MAAa,gBAAA,4CAAeA,CAAAA,CAAAA,kBAAAA,CAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
|
package/dist/apiContracts.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
//#region src/schemas/apiContracts.d.ts
|
|
2
|
-
/** This
|
|
2
|
+
/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
|
|
3
3
|
export declare const apiContracts: {
|
|
4
4
|
version: 1;
|
|
5
5
|
protocols?: Record<string, string> | undefined;
|
package/dist/apiContracts.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { defineApiContract } from "@agimon-ai/po-core/apiContracts";
|
|
2
2
|
//#region src/schemas/apiContracts.ts
|
|
3
|
-
/** This
|
|
3
|
+
/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
|
|
4
4
|
const apiContracts = defineApiContract({
|
|
5
5
|
version: 1,
|
|
6
6
|
http: [],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This
|
|
1
|
+
{"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAa,eAAe,kBAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { access, readFile, writeFile } from "node:fs/promises";
|
|
1
|
+
import { BACKGROUND_CONTEXT, FileTooLargeError, getOrThrow, readBoundedFile, withAbortSignal } from "@agimon-ai/po-core/platform";
|
|
3
2
|
import { applyHashlineEdits, normalizeFileTag, normalizeToLf, stripBom } from "@agimon-ai/po-hashline";
|
|
4
3
|
import { computeFileTag, decodeUtf8, displayPath, resolveInputPath } from "@agimon-ai/po-hashline/files";
|
|
5
4
|
import { generateDiffString, generateUnifiedPatch, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
@@ -20,11 +19,11 @@ const EditParamsSchema = Type.Object({
|
|
|
20
19
|
});
|
|
21
20
|
//#endregion
|
|
22
21
|
//#region src/services/editTool/index.ts
|
|
23
|
-
function createHashlineEditTool() {
|
|
22
|
+
function createHashlineEditTool(filesystem) {
|
|
24
23
|
return {
|
|
25
24
|
name: "edit",
|
|
26
25
|
label: "edit",
|
|
27
|
-
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range.",
|
|
26
|
+
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.",
|
|
28
27
|
promptSnippet: "Edit files with snapshot-bound hashline ranges",
|
|
29
28
|
promptGuidelines: [
|
|
30
29
|
"Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.",
|
|
@@ -35,32 +34,41 @@ function createHashlineEditTool() {
|
|
|
35
34
|
parameters: EditParamsSchema,
|
|
36
35
|
executionMode: "parallel",
|
|
37
36
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
38
|
-
return executeHashlineEdit(params, ctx.cwd, signal);
|
|
37
|
+
return executeHashlineEdit(params, ctx.cwd, signal, typeof filesystem === "function" ? filesystem() : filesystem);
|
|
39
38
|
}
|
|
40
39
|
};
|
|
41
40
|
}
|
|
42
|
-
function createHeadlessEditTool() {
|
|
41
|
+
function createHeadlessEditTool(filesystem) {
|
|
43
42
|
return {
|
|
44
43
|
name: "edit",
|
|
45
44
|
label: "edit",
|
|
46
|
-
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range.",
|
|
45
|
+
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.",
|
|
47
46
|
promptSnippet: "Edit files with snapshot-bound hashline ranges",
|
|
48
47
|
promptGuidelines: ["Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.", "Pass one anchor such as 5#abc in each from and to value. Do not paste tagged lines or multiline blocks."],
|
|
49
48
|
parameters: EditParamsSchema,
|
|
50
49
|
executionMode: "parallel",
|
|
51
|
-
execute: (_toolCallId, params, signal, _onUpdate, context) => executeHashlineEdit(params, context.cwd, signal)
|
|
50
|
+
execute: (_toolCallId, params, signal, _onUpdate, context) => executeHashlineEdit(params, context.cwd, signal, typeof filesystem === "function" ? filesystem() : filesystem)
|
|
52
51
|
};
|
|
53
52
|
}
|
|
54
53
|
function assertNotAborted(signal) {
|
|
55
54
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
56
55
|
}
|
|
57
|
-
async function executeHashlineEdit(params, cwd, signal) {
|
|
56
|
+
async function executeHashlineEdit(params, cwd, signal, filesystem) {
|
|
58
57
|
const absolutePath = resolveInputPath(params.path, cwd);
|
|
58
|
+
const context = signal ? withAbortSignal(signal, BACKGROUND_CONTEXT) : BACKGROUND_CONTEXT;
|
|
59
|
+
const readSnapshot = async () => {
|
|
60
|
+
try {
|
|
61
|
+
return Buffer.from(await readBoundedFile(filesystem, absolutePath, 8388608, context));
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof FileTooLargeError) throw new Error("File is over 8 MiB, hashline edit refuses; use runner log tools for logs.", { cause: error });
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
59
67
|
const expectedHash = normalizeFileTag(params.hash);
|
|
60
68
|
return withFileMutationQueue(absolutePath, async () => {
|
|
61
69
|
assertNotAborted(signal);
|
|
62
|
-
await
|
|
63
|
-
const beforeBytes = await
|
|
70
|
+
getOrThrow(await filesystem.fileInfo(absolutePath, context));
|
|
71
|
+
const beforeBytes = await readSnapshot();
|
|
64
72
|
assertNotAborted(signal);
|
|
65
73
|
const actualHash = computeFileTag(beforeBytes);
|
|
66
74
|
if (actualHash !== expectedHash) throw new Error(`Stale file hash ${expectedHash}. Current hash is ${actualHash}. Re-read the file and retry.`);
|
|
@@ -83,11 +91,11 @@ async function executeHashlineEdit(params, cwd, signal) {
|
|
|
83
91
|
firstChangedLine: diff.firstChangedLine
|
|
84
92
|
};
|
|
85
93
|
assertNotAborted(signal);
|
|
86
|
-
if (!(await
|
|
94
|
+
if (!(await readSnapshot()).equals(beforeBytes)) throw new Error("The file changed while the edit was being prepared. Re-read it and retry.");
|
|
87
95
|
assertNotAborted(signal);
|
|
88
96
|
if (applied.content !== before) {
|
|
89
97
|
const output = Buffer.from(`${hasBom ? "" : ""}${editedText}`, "utf8");
|
|
90
|
-
await writeFile(absolutePath, output);
|
|
98
|
+
getOrThrow(await filesystem.writeFile(absolutePath, output, BACKGROUND_CONTEXT));
|
|
91
99
|
}
|
|
92
100
|
const count = applied.edits.length;
|
|
93
101
|
const noun = count === 1 ? "range" : "ranges";
|
|
@@ -154,4 +162,4 @@ function replacementLines(content) {
|
|
|
154
162
|
//#endregion
|
|
155
163
|
export { HashlineRangeSchema as a, EditParamsSchema as i, createHeadlessEditTool as n, executeHashlineEdit as r, createHashlineEditTool as t };
|
|
156
164
|
|
|
157
|
-
//# sourceMappingURL=editTool
|
|
165
|
+
//# sourceMappingURL=editTool-DVt2xCNP.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"editTool-DVt2xCNP.mjs","names":[],"sources":["../src/schemas/editTool.ts","../src/services/editTool/index.ts"],"sourcesContent":["import { type Static, Type } from 'typebox';\n\nexport const HashlineRangeSchema = Type.Object({\n from: Type.String({ description: 'One inclusive starting anchor, for example 5#abc. Do not paste multiple lines.' }),\n to: Type.String({ description: 'One inclusive ending anchor, for example 8#def. Do not paste multiple lines.' }),\n content: Type.Optional(\n Type.Union([\n Type.String({ description: 'Replacement content. Empty content deletes the selected lines.' }),\n Type.Null({ description: 'Delete the selected lines.' }),\n ]),\n ),\n});\n\nexport const EditParamsSchema = Type.Object({\n path: Type.String({ description: 'Path to the file returned by a compatible hashline read or grep tool.' }),\n hash: Type.String({ description: 'Eight-character exact-byte file tag returned by read or grep.' }),\n edits: Type.Array(HashlineRangeSchema, {\n minItems: 1,\n description: 'Non-overlapping inclusive ranges from the same original snapshot.',\n }),\n});\n\nexport type HashlineRange = Static<typeof HashlineRangeSchema>;\nexport type EditParams = Static<typeof EditParamsSchema>;\n","import type { PoHeadlessExecutionContext, PoHeadlessTool, PoHeadlessToolResult } from '@agimon-ai/po-core/headless';\nimport {\n BACKGROUND_CONTEXT,\n FileTooLargeError,\n getOrThrow,\n readBoundedFile,\n withAbortSignal,\n type FileSystem,\n} from '@agimon-ai/po-core/platform';\nimport {\n applyHashlineEdits,\n normalizeFileTag,\n normalizeToLf,\n stripBom,\n type PreparedHashlineEdit,\n} from '@agimon-ai/po-hashline';\nimport { computeFileTag, decodeUtf8, displayPath, resolveInputPath } from '@agimon-ai/po-hashline/files';\nimport {\n generateDiffString,\n generateUnifiedPatch,\n withFileMutationQueue,\n type EditToolDetails,\n} from '@earendil-works/pi-coding-agent';\nimport type { ToolDefinition } from '@earendil-works/pi-coding-agent';\n\nimport { EditParamsSchema, type EditParams } from '../../schemas/editTool';\n\nexport function createHashlineEditTool(\n filesystem: FileSystem | (() => FileSystem),\n): ToolDefinition<typeof EditParamsSchema> {\n return {\n name: 'edit',\n label: 'edit',\n description:\n 'Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.',\n promptSnippet: 'Edit files with snapshot-bound hashline ranges',\n promptGuidelines: [\n 'Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.',\n 'Pass one anchor such as 5#abc in each from and to value. Do not paste tagged lines or multiline blocks.',\n 'Put multiple disjoint changes to one file in one edit call. All anchors must describe the original snapshot.',\n 'Omit content or pass an empty string to delete an inclusive range. Merge overlapping ranges before calling edit.',\n ],\n parameters: EditParamsSchema,\n executionMode: 'parallel',\n async execute(_toolCallId, params, signal, _onUpdate, ctx) {\n return executeHashlineEdit(\n params as EditParams,\n ctx.cwd,\n signal,\n typeof filesystem === 'function' ? filesystem() : filesystem,\n );\n },\n };\n}\n\nexport function createHeadlessEditTool(\n filesystem: FileSystem | (() => FileSystem),\n): PoHeadlessTool<typeof EditParamsSchema> {\n return {\n name: 'edit',\n label: 'edit',\n description:\n 'Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.',\n promptSnippet: 'Edit files with snapshot-bound hashline ranges',\n promptGuidelines: [\n 'Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.',\n 'Pass one anchor such as 5#abc in each from and to value. Do not paste tagged lines or multiline blocks.',\n ],\n parameters: EditParamsSchema,\n executionMode: 'parallel',\n execute: (\n _toolCallId: string,\n params: EditParams,\n signal: AbortSignal | undefined,\n _onUpdate: ((result: PoHeadlessToolResult) => void) | undefined,\n context: PoHeadlessExecutionContext,\n ) => executeHashlineEdit(params, context.cwd, signal, typeof filesystem === 'function' ? filesystem() : filesystem),\n };\n}\n\nexport function assertNotAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Error('Operation aborted');\n}\n\nexport async function executeHashlineEdit(\n params: EditParams,\n cwd: string,\n signal: AbortSignal | undefined,\n filesystem: FileSystem,\n): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const context = signal ? withAbortSignal(signal, BACKGROUND_CONTEXT) : BACKGROUND_CONTEXT;\n const readSnapshot = async (): Promise<Buffer> => {\n try {\n return Buffer.from(await readBoundedFile(filesystem, absolutePath, 8 * 1024 * 1024, context));\n } catch (error) {\n if (error instanceof FileTooLargeError) {\n throw new Error('File is over 8 MiB, hashline edit refuses; use runner log tools for logs.', { cause: error });\n }\n throw error;\n }\n };\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n getOrThrow(await filesystem.fileInfo(absolutePath, context));\n const beforeBytes = await readSnapshot();\n assertNotAborted(signal);\n\n const actualHash = computeFileTag(beforeBytes);\n if (actualHash !== expectedHash) {\n throw new Error(`Stale file hash ${expectedHash}. Current hash is ${actualHash}. Re-read the file and retry.`);\n }\n\n const hasBom = beforeBytes.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf]));\n const decoded = decodeUtf8(beforeBytes, params.path);\n const withoutBom = stripBom(decoded);\n const before = normalizeToLf(withoutBom);\n const applied = applyHashlineEdits(before, params.edits);\n const editedText = restoreOriginalLineEndings(withoutBom, applied.edits);\n if (normalizeToLf(editedText) !== applied.content) {\n throw new Error('Could not preserve the file line endings safely. The file was not changed.');\n }\n const diff = generateDiffString(before, applied.content);\n const patch = generateUnifiedPatch(displayPath(absolutePath, cwd), before, applied.content);\n const details: EditToolDetails = { diff: diff.diff, patch, firstChangedLine: diff.firstChangedLine };\n\n assertNotAborted(signal);\n const currentBytes = await readSnapshot();\n if (!currentBytes.equals(beforeBytes)) {\n throw new Error('The file changed while the edit was being prepared. Re-read it and retry.');\n }\n assertNotAborted(signal);\n\n if (applied.content !== before) {\n const output = Buffer.from(`${hasBom ? '\\ufeff' : ''}${editedText}`, 'utf8');\n getOrThrow(await filesystem.writeFile(absolutePath, output, BACKGROUND_CONTEXT));\n }\n\n const count = applied.edits.length;\n const noun = count === 1 ? 'range' : 'ranges';\n const message =\n applied.content === before ? `No changes needed in ${params.path}.` : `Edited ${params.path} (${count} ${noun}).`;\n return { content: [{ type: 'text', text: `${message} Re-read before editing it again.` }], details };\n });\n}\n\ninterface LineToken {\n readonly text: string;\n readonly ending: '\\r\\n' | '\\n' | '\\r' | '';\n}\n\nfunction restoreOriginalLineEndings(original: string, edits: readonly PreparedHashlineEdit[]): string {\n const tokens = tokenizeLines(original);\n const defaultEnding = tokens.find((token) => token.ending !== '')?.ending ?? '\\n';\n for (const edit of [...edits].reverse()) {\n const start = edit.from.line - 1;\n const count = edit.to.line - edit.from.line + 1;\n const removed = tokens.slice(start, start + count);\n const inheritedEnding = removed.at(-1)?.ending ?? '';\n const internalEnding = removed.find((token) => token.ending !== '')?.ending ?? defaultEnding;\n const lines = replacementLines(edit.content);\n if (lines.length === 0 && removed.at(-1)?.ending === '' && start > 0) {\n const previous = tokens[start - 1];\n if (previous) tokens[start - 1] = { ...previous, ending: '' };\n }\n const replacements = lines.map<LineToken>((text, index) => ({\n text,\n ending: index === lines.length - 1 ? inheritedEnding : internalEnding,\n }));\n tokens.splice(start, count, ...replacements);\n }\n return tokens.map((token) => `${token.text}${token.ending}`).join('');\n}\n\nfunction tokenizeLines(content: string): LineToken[] {\n const tokens: LineToken[] = [];\n let start = 0;\n for (let index = 0; index < content.length; index += 1) {\n const character = content[index];\n if (character !== '\\r' && character !== '\\n') continue;\n const ending = character === '\\r' && content[index + 1] === '\\n' ? '\\r\\n' : character;\n tokens.push({ text: content.slice(start, index), ending });\n if (ending === '\\r\\n') index += 1;\n start = index + 1;\n }\n tokens.push({ text: content.slice(start), ending: '' });\n return tokens;\n}\n\nfunction replacementLines(content: string | null): string[] {\n if (content === null || content === '') return [];\n const normalized = normalizeToLf(content);\n const trimmed = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n return trimmed === '' ? [] : trimmed.split('\\n');\n}\n"],"mappings":";;;;;;AAEA,MAAa,sBAAsB,KAAK,OAAO;CAC7C,MAAM,KAAK,OAAO,EAAE,aAAa,iFAAiF,CAAC;CACnH,IAAI,KAAK,OAAO,EAAE,aAAa,+EAA+E,CAAC;CAC/G,SAAS,KAAK,SACZ,KAAK,MAAM,CACT,KAAK,OAAO,EAAE,aAAa,iEAAiE,CAAC,GAC7F,KAAK,KAAK,EAAE,aAAa,6BAA6B,CAAC,CACzD,CAAC,CACH;AACF,CAAC;AAED,MAAa,mBAAmB,KAAK,OAAO;CAC1C,MAAM,KAAK,OAAO,EAAE,aAAa,wEAAwE,CAAC;CAC1G,MAAM,KAAK,OAAO,EAAE,aAAa,gEAAgE,CAAC;CAClG,OAAO,KAAK,MAAM,qBAAqB;EACrC,UAAU;EACV,aAAa;CACf,CAAC;AACH,CAAC;;;ACOD,SAAgB,uBACd,YACyC;CACzC,OAAO;EACL,MAAM;EACN,OAAO;EACP,aACE;EACF,eAAe;EACf,kBAAkB;GAChB;GACA;GACA;GACA;EACF;EACA,YAAY;EACZ,eAAe;EACf,MAAM,QAAQ,aAAa,QAAQ,QAAQ,WAAW,KAAK;GACzD,OAAO,oBACL,QACA,IAAI,K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AAY,QAAQ,YAAY,IAAI,OAAO,CAAC;CAChD,MAAM,aAAa,cAAc,OAAO;CACxC,MAAM,UAAU,WAAW,SAAS,IAAI,IAAI,WAAW,MAAM,GAAG,EAAE,IAAI;CACtE,OAAO,YAAY,KAAK,CAAC,IAAI,QAAQ,MAAM,IAAI;AACjD"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
let
|
|
2
|
-
let node_fs_promises = require("node:fs/promises");
|
|
1
|
+
let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
|
|
3
2
|
let _agimon_ai_po_hashline = require("@agimon-ai/po-hashline");
|
|
4
3
|
let _agimon_ai_po_hashline_files = require("@agimon-ai/po-hashline/files");
|
|
5
4
|
let _earendil_works_pi_coding_agent = require("@earendil-works/pi-coding-agent");
|
|
@@ -20,11 +19,11 @@ const EditParamsSchema = typebox.Type.Object({
|
|
|
20
19
|
});
|
|
21
20
|
//#endregion
|
|
22
21
|
//#region src/services/editTool/index.ts
|
|
23
|
-
function createHashlineEditTool() {
|
|
22
|
+
function createHashlineEditTool(filesystem) {
|
|
24
23
|
return {
|
|
25
24
|
name: "edit",
|
|
26
25
|
label: "edit",
|
|
27
|
-
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range.",
|
|
26
|
+
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.",
|
|
28
27
|
promptSnippet: "Edit files with snapshot-bound hashline ranges",
|
|
29
28
|
promptGuidelines: [
|
|
30
29
|
"Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.",
|
|
@@ -35,32 +34,41 @@ function createHashlineEditTool() {
|
|
|
35
34
|
parameters: EditParamsSchema,
|
|
36
35
|
executionMode: "parallel",
|
|
37
36
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
38
|
-
return executeHashlineEdit(params, ctx.cwd, signal);
|
|
37
|
+
return executeHashlineEdit(params, ctx.cwd, signal, typeof filesystem === "function" ? filesystem() : filesystem);
|
|
39
38
|
}
|
|
40
39
|
};
|
|
41
40
|
}
|
|
42
|
-
function createHeadlessEditTool() {
|
|
41
|
+
function createHeadlessEditTool(filesystem) {
|
|
43
42
|
return {
|
|
44
43
|
name: "edit",
|
|
45
44
|
label: "edit",
|
|
46
|
-
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range.",
|
|
45
|
+
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.",
|
|
47
46
|
promptSnippet: "Edit files with snapshot-bound hashline ranges",
|
|
48
47
|
promptGuidelines: ["Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.", "Pass one anchor such as 5#abc in each from and to value. Do not paste tagged lines or multiline blocks."],
|
|
49
48
|
parameters: EditParamsSchema,
|
|
50
49
|
executionMode: "parallel",
|
|
51
|
-
execute: (_toolCallId, params, signal, _onUpdate, context) => executeHashlineEdit(params, context.cwd, signal)
|
|
50
|
+
execute: (_toolCallId, params, signal, _onUpdate, context) => executeHashlineEdit(params, context.cwd, signal, typeof filesystem === "function" ? filesystem() : filesystem)
|
|
52
51
|
};
|
|
53
52
|
}
|
|
54
53
|
function assertNotAborted(signal) {
|
|
55
54
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
56
55
|
}
|
|
57
|
-
async function executeHashlineEdit(params, cwd, signal) {
|
|
56
|
+
async function executeHashlineEdit(params, cwd, signal, filesystem) {
|
|
58
57
|
const absolutePath = (0, _agimon_ai_po_hashline_files.resolveInputPath)(params.path, cwd);
|
|
58
|
+
const context = signal ? (0, _agimon_ai_po_core_platform.withAbortSignal)(signal, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT) : _agimon_ai_po_core_platform.BACKGROUND_CONTEXT;
|
|
59
|
+
const readSnapshot = async () => {
|
|
60
|
+
try {
|
|
61
|
+
return Buffer.from(await (0, _agimon_ai_po_core_platform.readBoundedFile)(filesystem, absolutePath, 8388608, context));
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof _agimon_ai_po_core_platform.FileTooLargeError) throw new Error("File is over 8 MiB, hashline edit refuses; use runner log tools for logs.", { cause: error });
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
59
67
|
const expectedHash = (0, _agimon_ai_po_hashline.normalizeFileTag)(params.hash);
|
|
60
68
|
return (0, _earendil_works_pi_coding_agent.withFileMutationQueue)(absolutePath, async () => {
|
|
61
69
|
assertNotAborted(signal);
|
|
62
|
-
|
|
63
|
-
const beforeBytes = await (
|
|
70
|
+
(0, _agimon_ai_po_core_platform.getOrThrow)(await filesystem.fileInfo(absolutePath, context));
|
|
71
|
+
const beforeBytes = await readSnapshot();
|
|
64
72
|
assertNotAborted(signal);
|
|
65
73
|
const actualHash = (0, _agimon_ai_po_hashline_files.computeFileTag)(beforeBytes);
|
|
66
74
|
if (actualHash !== expectedHash) throw new Error(`Stale file hash ${expectedHash}. Current hash is ${actualHash}. Re-read the file and retry.`);
|
|
@@ -83,11 +91,11 @@ async function executeHashlineEdit(params, cwd, signal) {
|
|
|
83
91
|
firstChangedLine: diff.firstChangedLine
|
|
84
92
|
};
|
|
85
93
|
assertNotAborted(signal);
|
|
86
|
-
if (!(await (
|
|
94
|
+
if (!(await readSnapshot()).equals(beforeBytes)) throw new Error("The file changed while the edit was being prepared. Re-read it and retry.");
|
|
87
95
|
assertNotAborted(signal);
|
|
88
96
|
if (applied.content !== before) {
|
|
89
97
|
const output = Buffer.from(`${hasBom ? "" : ""}${editedText}`, "utf8");
|
|
90
|
-
|
|
98
|
+
(0, _agimon_ai_po_core_platform.getOrThrow)(await filesystem.writeFile(absolutePath, output, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
|
|
91
99
|
}
|
|
92
100
|
const count = applied.edits.length;
|
|
93
101
|
const noun = count === 1 ? "range" : "ranges";
|
|
@@ -183,4 +191,4 @@ Object.defineProperty(exports, "executeHashlineEdit", {
|
|
|
183
191
|
}
|
|
184
192
|
});
|
|
185
193
|
|
|
186
|
-
//# sourceMappingURL=editTool-
|
|
194
|
+
//# sourceMappingURL=editTool-VO-ySAzl.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"editTool-VO-ySAzl.cjs","names":["Type","resolveInputPath","withAbortSignal","BACKGROUND_CONTEXT","readBoundedFile","FileTooLargeError","normalizeFileTag","withFileMutationQueue","computeFileTag","decodeUtf8","stripBom","normalizeToLf","applyHashlineEdits","generateDiffString","generateUnifiedPatch","displayPath"],"sources":["../src/schemas/editTool.ts","../src/services/editTool/index.ts"],"sourcesContent":["import { type Static, Type } from 'typebox';\n\nexport const HashlineRangeSchema = Type.Object({\n from: Type.String({ description: 'One inclusive starting anchor, for example 5#abc. Do not paste multiple lines.' }),\n to: Type.String({ description: 'One inclusive ending anchor, for example 8#def. Do not paste multiple lines.' }),\n content: Type.Optional(\n Type.Union([\n Type.String({ description: 'Replacement content. Empty content deletes the selected lines.' }),\n Type.Null({ description: 'Delete the selected lines.' }),\n ]),\n ),\n});\n\nexport const EditParamsSchema = Type.Object({\n path: Type.String({ description: 'Path to the file returned by a compatible hashline read or grep tool.' }),\n hash: Type.String({ description: 'Eight-character exact-byte file tag returned by read or grep.' }),\n edits: Type.Array(HashlineRangeSchema, {\n minItems: 1,\n description: 'Non-overlapping inclusive ranges from the same original snapshot.',\n }),\n});\n\nexport type HashlineRange = Static<typeof HashlineRangeSchema>;\nexport type EditParams = Static<typeof EditParamsSchema>;\n","import type { PoHeadlessExecutionContext, PoHeadlessTool, PoHeadlessToolResult } from '@agimon-ai/po-core/headless';\nimport {\n BACKGROUND_CONTEXT,\n FileTooLargeError,\n getOrThrow,\n readBoundedFile,\n withAbortSignal,\n type FileSystem,\n} from '@agimon-ai/po-core/platform';\nimport {\n applyHashlineEdits,\n normalizeFileTag,\n normalizeToLf,\n stripBom,\n type PreparedHashlineEdit,\n} from '@agimon-ai/po-hashline';\nimport { computeFileTag, decodeUtf8, displayPath, resolveInputPath } from '@agimon-ai/po-hashline/files';\nimport {\n generateDiffString,\n generateUnifiedPatch,\n withFileMutationQueue,\n type EditToolDetails,\n} from '@earendil-works/pi-coding-agent';\nimport type { ToolDefinition } from '@earendil-works/pi-coding-agent';\n\nimport { EditParamsSchema, type EditParams } from '../../schemas/editTool';\n\nexport function createHashlineEditTool(\n filesystem: FileSystem | (() => FileSystem),\n): ToolDefinition<typeof EditParamsSchema> {\n return {\n name: 'edit',\n label: 'edit',\n description:\n 'Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.',\n promptSnippet: 'Edit files with snapshot-bound hashline ranges',\n promptGuidelines: [\n 'Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.',\n 'Pass one anchor such as 5#abc in each from and to value. Do not paste tagged lines or multiline blocks.',\n 'Put multiple disjoint changes to one file in one edit call. All anchors must describe the original snapshot.',\n 'Omit content or pass an empty string to delete an inclusive range. Merge overlapping ranges before calling edit.',\n ],\n parameters: EditParamsSchema,\n executionMode: 'parallel',\n async execute(_toolCallId, params, signal, _onUpdate, ctx) {\n return executeHashlineEdit(\n params as EditParams,\n ctx.cwd,\n signal,\n typeof filesystem === 'function' ? filesystem() : filesystem,\n );\n },\n };\n}\n\nexport function createHeadlessEditTool(\n filesystem: FileSystem | (() => FileSystem),\n): PoHeadlessTool<typeof EditParamsSchema> {\n return {\n name: 'edit',\n label: 'edit',\n description:\n 'Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.',\n promptSnippet: 'Edit files with snapshot-bound hashline ranges',\n promptGuidelines: [\n 'Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.',\n 'Pass one anchor such as 5#abc in each from and to value. Do not paste tagged lines or multiline blocks.',\n ],\n parameters: EditParamsSchema,\n executionMode: 'parallel',\n execute: (\n _toolCallId: string,\n params: EditParams,\n signal: AbortSignal | undefined,\n _onUpdate: ((result: PoHeadlessToolResult) => void) | undefined,\n context: PoHeadlessExecutionContext,\n ) => executeHashlineEdit(params, context.cwd, signal, typeof filesystem === 'function' ? filesystem() : filesystem),\n };\n}\n\nexport function assertNotAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Error('Operation aborted');\n}\n\nexport async function executeHashlineEdit(\n params: EditParams,\n cwd: string,\n signal: AbortSignal | undefined,\n filesystem: FileSystem,\n): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const context = signal ? withAbortSignal(signal, BACKGROUND_CONTEXT) : BACKGROUND_CONTEXT;\n const readSnapshot = async (): Promise<Buffer> => {\n try {\n return Buffer.from(await readBoundedFile(filesystem, absolutePath, 8 * 1024 * 1024, context));\n } catch (error) {\n if (error instanceof FileTooLargeError) {\n throw new Error('File is over 8 MiB, hashline edit refuses; use runner log tools for logs.', { cause: error });\n }\n throw error;\n }\n };\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n getOrThrow(await filesystem.fileInfo(absolutePath, context));\n const beforeBytes = await readSnapshot();\n assertNotAborted(signal);\n\n const actualHash = computeFileTag(beforeBytes);\n if (actualHash !== expectedHash) {\n throw new Error(`Stale file hash ${expectedHash}. Current hash is ${actualHash}. Re-read the file and retry.`);\n }\n\n const hasBom = beforeBytes.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf]));\n const decoded = decodeUtf8(beforeBytes, params.path);\n const withoutBom = stripBom(decoded);\n const before = normalizeToLf(withoutBom);\n const applied = applyHashlineEdits(before, params.edits);\n const editedText = restoreOriginalLineEndings(withoutBom, applied.edits);\n if (normalizeToLf(editedText) !== applied.content) {\n throw new Error('Could not preserve the file line endings safely. The file was not changed.');\n }\n const diff = generateDiffString(before, applied.content);\n const patch = generateUnifiedPatch(displayPath(absolutePath, cwd), before, applied.content);\n const details: EditToolDetails = { diff: diff.diff, patch, firstChangedLine: diff.firstChangedLine };\n\n assertNotAborted(signal);\n const currentBytes = await readSnapshot();\n if (!currentBytes.equals(beforeBytes)) {\n throw new Error('The file changed while the edit was being prepared. Re-read it and retry.');\n }\n assertNotAborted(signal);\n\n if (applied.content !== before) {\n const output = Buffer.from(`${hasBom ? '\\ufeff' : ''}${editedText}`, 'utf8');\n getOrThrow(await filesystem.writeFile(absolutePath, output, BACKGROUND_CONTEXT));\n }\n\n const count = applied.edits.length;\n const noun = count === 1 ? 'range' : 'ranges';\n const message =\n applied.content === before ? `No changes needed in ${params.path}.` : `Edited ${params.path} (${count} ${noun}).`;\n return { content: [{ type: 'text', text: `${message} Re-read before editing it again.` }], details };\n });\n}\n\ninterface LineToken {\n readonly text: string;\n readonly ending: '\\r\\n' | '\\n' | '\\r' | '';\n}\n\nfunction restoreOriginalLineEndings(original: string, edits: readonly PreparedHashlineEdit[]): string {\n const tokens = tokenizeLines(original);\n const defaultEnding = tokens.find((token) => token.ending !== '')?.ending ?? '\\n';\n for (const edit of [...edits].reverse()) {\n const start = edit.from.line - 1;\n const count = edit.to.line - edit.from.line + 1;\n const removed = tokens.slice(start, start + count);\n const inheritedEnding = removed.at(-1)?.ending ?? '';\n const internalEnding = removed.find((token) => token.ending !== '')?.ending ?? defaultEnding;\n const lines = replacementLines(edit.content);\n if (lines.length === 0 && removed.at(-1)?.ending === '' && start > 0) {\n const previous = tokens[start - 1];\n if (previous) tokens[start - 1] = { ...previous, ending: '' };\n }\n const replacements = lines.map<LineToken>((text, index) => ({\n text,\n ending: index === lines.length - 1 ? inheritedEnding : internalEnding,\n }));\n tokens.splice(start, count, ...replacements);\n }\n return tokens.map((token) => `${token.text}${token.ending}`).join('');\n}\n\nfunction tokenizeLines(content: string): LineToken[] {\n const tokens: LineToken[] = [];\n let start = 0;\n for (let index = 0; index < content.length; index += 1) {\n const character = content[index];\n if (character !== '\\r' && character !== '\\n') continue;\n const ending = character === '\\r' && content[index + 1] === '\\n' ? '\\r\\n' : character;\n tokens.push({ text: content.slice(start, index), ending });\n if (ending === '\\r\\n') index += 1;\n start = index + 1;\n }\n tokens.push({ text: content.slice(start), ending: '' });\n return tokens;\n}\n\nfunction replacementLines(content: string | null): string[] {\n if (content === null || content === '') return [];\n const normalized = normalizeToLf(content);\n const trimmed = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n return trimmed === '' ? [] : trimmed.split('\\n');\n}\n"],"mappings":";;;;;;AAEA,MAAa,sBAAsBA,QAAAA,KAAK,OAAO;CAC7C,MAAMA,QAAAA,KAAK,OAAO,EAAE,aAAa,iFAAiF,CAAC;CACnH,IAAIA,QAAAA,KAAK,OAAO,EAAE,aAAa,+EAA+E,CAAC;CAC/G,SAASA,QAAAA,KAAK,SACZA,QAAAA,KAAK,MAAM,CACTA,QAAAA,KAAK,OAAO,EAAE,aAAa,iEAAiE,CAAC,GAC7FA,QAAAA,KAAK,KAAK,EAAE,aAAa,6BAA6B,CAAC,CACzD,CAAC,CACH;AACF,CAAC;AAED,MAAa,mBAAmBA,QAAAA,KAAK,OAAO;CAC1C,MAAMA,QAAAA,KAAK,OAAO,EAAE,aAAa,wEAAwE,CAAC;CAC1G,MAAMA,QAAAA,KAAK,OAAO,EAAE,aAAa,gEAAgE,CAAC;CAClG,OAAOA,QAAAA,KAAK,MAAM,qBAAqB;EACrC,UAAU;EACV,aAAa;CACf,CAAC;AACH,CAAC;;;ACOD,SAAgB,uBACd,YACyC;CACzC,OAAO;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GAAG,MAAM,OAAO,MAAM,QAAQ,CAAC,CAAC,KAAK,EAAE;AACtE;AAEA,SAAS,cAAc,SAA8B;CACnD,MAAM,SAAsB,CAAC;CAC7B,IAAI,QAAQ;CACZ,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS,GAAG;EACtD,MAAM,YAAY,QAAQ;EAC1B,IAAI,cAAc,QAAQ,cAAc,MAAM;EAC9C,MAAM,SAAS,cAAc,QAAQ,QAAQ,QAAQ,OAAO,OAAO,SAAS;EAC5E,OAAO,KAAK;GAAE,MAAM,QAAQ,MAAM,OAAO,KAAK;GAAG;EAAO,CAAC;EACzD,IAAI,WAAW,QAAQ,SAAS;EAChC,QAAQ,QAAQ;CAClB;CACA,OAAO,KAAK;EAAE,MAAM,QAAQ,MAAM,KAAK;EAAG,QAAQ;CAAG,CAAC;CACtD,OAAO;AACT;AAEA,SAAS,iBAAiB,SAAkC;CAC1D,IAAI,YAAY,QAAQ,YAAY,IAAI,OAAO,CAAC;CAChD,MAAM,cAAA,GAAaQ,uBAAAA,cAAAA,CAAc,OAAO;CACxC,MAAM,UAAU,WAAW,SAAS,IAAI,IAAI,WAAW,MAAM,GAAG,EAAE,IAAI;CACtE,OAAO,YAAY,KAAK,CAAC,IAAI,QAAQ,MAAM,IAAI;AACjD"}
|
package/dist/extensions/mcp.cjs
CHANGED
|
@@ -3,8 +3,7 @@ Object.defineProperties(exports, {
|
|
|
3
3
|
[Symbol.toStringTag]: { value: "Module" }
|
|
4
4
|
});
|
|
5
5
|
let _agimon_ai_po_core_mcpFacet = require("@agimon-ai/po-core/mcpFacet");
|
|
6
|
-
let
|
|
7
|
-
let node_fs_promises = require("node:fs/promises");
|
|
6
|
+
let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
|
|
8
7
|
let _agimon_ai_po_hashline = require("@agimon-ai/po-hashline");
|
|
9
8
|
let _agimon_ai_po_hashline_files = require("@agimon-ai/po-hashline/files");
|
|
10
9
|
let _earendil_works_pi_coding_agent = require("@earendil-works/pi-coding-agent");
|
|
@@ -25,28 +24,37 @@ const EditParamsSchema = typebox.Type.Object({
|
|
|
25
24
|
});
|
|
26
25
|
//#endregion
|
|
27
26
|
//#region src/services/editTool/index.ts
|
|
28
|
-
function createHeadlessEditTool() {
|
|
27
|
+
function createHeadlessEditTool(filesystem) {
|
|
29
28
|
return {
|
|
30
29
|
name: "edit",
|
|
31
30
|
label: "edit",
|
|
32
|
-
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range.",
|
|
31
|
+
description: "Edit one file using its exact snapshot hash and inclusive anchors such as 5#abc from read or grep. Each from and to value must contain one anchor, not a pasted block. All ranges refer to the original snapshot. Empty or omitted content deletes a range. Files over 8 MiB are refused.",
|
|
33
32
|
promptSnippet: "Edit files with snapshot-bound hashline ranges",
|
|
34
33
|
promptGuidelines: ["Copy path, hash, and anchors from the latest compatible read or grep result. Re-read after every successful edit.", "Pass one anchor such as 5#abc in each from and to value. Do not paste tagged lines or multiline blocks."],
|
|
35
34
|
parameters: EditParamsSchema,
|
|
36
35
|
executionMode: "parallel",
|
|
37
|
-
execute: (_toolCallId, params, signal, _onUpdate, context) => executeHashlineEdit(params, context.cwd, signal)
|
|
36
|
+
execute: (_toolCallId, params, signal, _onUpdate, context) => executeHashlineEdit(params, context.cwd, signal, typeof filesystem === "function" ? filesystem() : filesystem)
|
|
38
37
|
};
|
|
39
38
|
}
|
|
40
39
|
function assertNotAborted(signal) {
|
|
41
40
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
42
41
|
}
|
|
43
|
-
async function executeHashlineEdit(params, cwd, signal) {
|
|
42
|
+
async function executeHashlineEdit(params, cwd, signal, filesystem) {
|
|
44
43
|
const absolutePath = (0, _agimon_ai_po_hashline_files.resolveInputPath)(params.path, cwd);
|
|
44
|
+
const context = signal ? (0, _agimon_ai_po_core_platform.withAbortSignal)(signal, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT) : _agimon_ai_po_core_platform.BACKGROUND_CONTEXT;
|
|
45
|
+
const readSnapshot = async () => {
|
|
46
|
+
try {
|
|
47
|
+
return Buffer.from(await (0, _agimon_ai_po_core_platform.readBoundedFile)(filesystem, absolutePath, 8388608, context));
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error instanceof _agimon_ai_po_core_platform.FileTooLargeError) throw new Error("File is over 8 MiB, hashline edit refuses; use runner log tools for logs.", { cause: error });
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
45
53
|
const expectedHash = (0, _agimon_ai_po_hashline.normalizeFileTag)(params.hash);
|
|
46
54
|
return (0, _earendil_works_pi_coding_agent.withFileMutationQueue)(absolutePath, async () => {
|
|
47
55
|
assertNotAborted(signal);
|
|
48
|
-
|
|
49
|
-
const beforeBytes = await (
|
|
56
|
+
(0, _agimon_ai_po_core_platform.getOrThrow)(await filesystem.fileInfo(absolutePath, context));
|
|
57
|
+
const beforeBytes = await readSnapshot();
|
|
50
58
|
assertNotAborted(signal);
|
|
51
59
|
const actualHash = (0, _agimon_ai_po_hashline_files.computeFileTag)(beforeBytes);
|
|
52
60
|
if (actualHash !== expectedHash) throw new Error(`Stale file hash ${expectedHash}. Current hash is ${actualHash}. Re-read the file and retry.`);
|
|
@@ -69,11 +77,11 @@ async function executeHashlineEdit(params, cwd, signal) {
|
|
|
69
77
|
firstChangedLine: diff.firstChangedLine
|
|
70
78
|
};
|
|
71
79
|
assertNotAborted(signal);
|
|
72
|
-
if (!(await (
|
|
80
|
+
if (!(await readSnapshot()).equals(beforeBytes)) throw new Error("The file changed while the edit was being prepared. Re-read it and retry.");
|
|
73
81
|
assertNotAborted(signal);
|
|
74
82
|
if (applied.content !== before) {
|
|
75
83
|
const output = Buffer.from(`${hasBom ? "" : ""}${editedText}`, "utf8");
|
|
76
|
-
|
|
84
|
+
(0, _agimon_ai_po_core_platform.getOrThrow)(await filesystem.writeFile(absolutePath, output, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
|
|
77
85
|
}
|
|
78
86
|
const count = applied.edits.length;
|
|
79
87
|
const noun = count === 1 ? "range" : "ranges";
|
|
@@ -139,10 +147,14 @@ function replacementLines(content) {
|
|
|
139
147
|
}
|
|
140
148
|
//#endregion
|
|
141
149
|
//#region src/extensions/workspaces/sessions/(backend)/tool/edit.mcp.ts
|
|
142
|
-
var edit_mcp_default = (0, _agimon_ai_po_core_mcpFacet.defineMcpTool)(() =>
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
150
|
+
var edit_mcp_default = (0, _agimon_ai_po_core_mcpFacet.defineMcpTool)((context) => {
|
|
151
|
+
const filesystem = context.services.get(_agimon_ai_po_core_platform.PO_FS_SERVICE);
|
|
152
|
+
if (!filesystem) throw new Error("Edit filesystem service is unavailable.");
|
|
153
|
+
return {
|
|
154
|
+
...createHeadlessEditTool(filesystem),
|
|
155
|
+
description: "Edit or patch an existing file in the Po session's repository on the host machine. Replace or delete line ranges using the file hash and anchors (such as 5#abc) from this server's read or grep tool. Each from and to holds one anchor; empty content deletes the range. Files over 8 MiB are refused."
|
|
156
|
+
};
|
|
157
|
+
});
|
|
146
158
|
//#endregion
|
|
147
159
|
//#region generated/mcp.ts
|
|
148
160
|
const at = (value, context) => typeof value === "function" ? value(context) : value;
|