@agimon-ai/po-edit 0.0.0-alpha.3 → 0.0.0-alpha.31

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 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
@@ -78,6 +78,6 @@ Maintained by [Agimon](https://agimon.ai/about).
78
78
 
79
79
  ## License
80
80
 
81
- MIT
81
+ 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
82
 
83
83
  The native tool declaration consumes `services/editTool`, and reusable factories and schemas are exposed through flat `src/exports`.
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  //#region src/schemas/apiContracts.ts
6
- /** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
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 facet 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"}
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"}
@@ -1,5 +1,5 @@
1
1
  //#region src/schemas/apiContracts.d.ts
2
- /** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
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;
@@ -1,6 +1,6 @@
1
1
  import { defineApiContract } from "@agimon-ai/po-core/apiContracts";
2
2
  //#region src/schemas/apiContracts.ts
3
- /** This facet contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
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 facet 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
+ {"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 +1 @@
1
- {"version":3,"file":"editTool--RaZ-yPH.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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type {\n DoomHeadlessExecutionContext,\n DoomHeadlessTool,\n DoomHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): DoomHeadlessTool<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.',\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: DoomHeadlessToolResult) => void) | undefined,\n context: DoomHeadlessExecutionContext,\n ) => executeHashlineEdit(params, context.cwd, signal),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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;;;ACMD,SAAgB,yBAAkE;CAChF,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,oBAAoB,QAAsB,IAAI,KAAK,MAAM;EAClE;CACF;AACF;AAEA,SAAgB,yBAAoE;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,aACE;EACF,eAAe;EACf,kBAAkB,CAChB,qHACA,yGACF;EACA,YAAY;EACZ,eAAe;EACf,UACE,aACA,QACA,QACA,WACA,YACG,oBAAoB,QAAQ,QAAQ,KAAK,MAAM;CACtD;AACF;AAEA,SAAgB,iBAAiB,QAAuC;CACtE,IAAI,QAAQ,SAAS,MAAM,IAAI,MAAM,mBAAmB;AAC1D;AAEA,eAAsB,oBACpB,QACA,KACA,QACk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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,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
+ {"version":3,"file":"editTool--RaZ-yPH.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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type { PoHeadlessExecutionContext, PoHeadlessTool, PoHeadlessToolResult } from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): 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.',\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),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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;;;ACED,SAAgB,yBAAkE;CAChF,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,oBAAoB,QAAsB,IAAI,KAAK,MAAM;EAClE;CACF;AACF;AAEA,SAAgB,yBAAkE;CAChF,OAAO;EACL,MAAM;EACN,OAAO;EACP,aACE;EACF,eAAe;EACf,kBAAkB,CAChB,qHACA,yGACF;EACA,YAAY;EACZ,eAAe;EACf,UACE,aACA,QACA,QACA,WACA,YACG,oBAAoB,QAAQ,QAAQ,KAAK,MAAM;CACtD;AACF;AAE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C;CACA,OAAO,OAAO,KAAK,UAAU,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,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 +1 @@
1
- {"version":3,"file":"editTool-BKaEjUdm.cjs","names":["Type","resolveInputPath","normalizeFileTag","withFileMutationQueue","access","constants","readFile","computeFileTag","decodeUtf8","stripBom","normalizeToLf","applyHashlineEdits","generateDiffString","generateUnifiedPatch","displayPath","writeFile"],"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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type {\n DoomHeadlessExecutionContext,\n DoomHeadlessTool,\n DoomHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): DoomHeadlessTool<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.',\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: DoomHeadlessToolResult) => void) | undefined,\n context: DoomHeadlessExecutionContext,\n ) => executeHashlineEdit(params, context.cwd, signal),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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;;;ACMD,SAAgB,yBAAkE;CAChF,OAAO;EACL,MAAM;EACN,OAAO;EACP,aACE;EACF,eAAe;EACf,kBAAkB;GAChB;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;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,GAAaL,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"}
1
+ {"version":3,"file":"editTool-BKaEjUdm.cjs","names":["Type","resolveInputPath","normalizeFileTag","withFileMutationQueue","access","constants","readFile","computeFileTag","decodeUtf8","stripBom","normalizeToLf","applyHashlineEdits","generateDiffString","generateUnifiedPatch","displayPath","writeFile"],"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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type { PoHeadlessExecutionContext, PoHeadlessTool, PoHeadlessToolResult } from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): 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.',\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),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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;\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cesContent":["import { defineMcpWidget, type DoomMcpWidgetProps } from '@agimon-ai/po-core/web';\nimport { McpToolFrame, McpToolFields, McpToolOutput } from '@agimon-ai/po-web-components';\n\nfunction EditMcpWidget(props: DoomMcpWidgetProps) {\n return (\n <McpToolFrame {...props} title=\"Edit file\">\n <McpToolFields\n fields={[\n ['Path', props.args.path],\n ['File revision', props.args.hash],\n ['Changes', Array.isArray(props.args.edits) ? props.args.edits.length : undefined],\n ]}\n />\n <McpToolOutput result={props.result} />\n </McpToolFrame>\n );\n}\n\nexport default defineMcpWidget(EditMcpWidget);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport type { ComponentType } from 'react';\nimport type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\nimport Widget0 from \"../src/extensions/workspaces/sessions/(frontend)/tool/edit.mcp\";\n\nexport const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {\n \"@agimon-ai/po-edit/edit\": Widget0,\n};\n"],"mappings":";;;;AAGA,SAAS,cAAc,OAA2B;CAChD,OACE,qBAAC,cAAD;EAAc,GAAI;EAAO,OAAM;EAA/B,UAAA,CACE,oBAAC,eAAD,EACE,QAAQ;GACN,CAAC,QAAQ,MAAM,KAAK,IAAI;GACxB,CAAC,iBAAiB,MAAM,KAAK,IAAI;GACjC,CAAC,WAAW,MAAM,QAAQ,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM,SAAS,KAAA,CAAS;EACnF,EACD,CAAA,GACD,oBAAC,eAAD,EAAe,QAAQ,MAAM,OAAS,CAAA,CAC1B;;AAElB;;;ACXA,MAAa,UAAuE,EAClF,2BDYa,gBAAgB,aCZFA,EAC7B"}
1
+ {"version":3,"file":"mcp-ui.mjs","names":["Widget0"],"sources":["../../src/extensions/workspaces/sessions/(frontend)/tool/edit.mcp.tsx","../../generated/mcp-ui.ts"],"sourcesContent":["import { defineMcpWidget, type PoMcpWidgetProps } from '@agimon-ai/po-core/web';\nimport { McpToolFrame, McpToolFields, McpToolOutput } from '@agimon-ai/po-web-components';\n\nfunction EditMcpWidget(props: PoMcpWidgetProps) {\n return (\n <McpToolFrame {...props} title=\"Edit file\">\n <McpToolFields\n fields={[\n ['Path', props.args.path],\n ['File revision', props.args.hash],\n ['Changes', Array.isArray(props.args.edits) ? props.args.edits.length : undefined],\n ]}\n />\n <McpToolOutput result={props.result} />\n </McpToolFrame>\n );\n}\n\nexport default defineMcpWidget(EditMcpWidget);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport type { ComponentType } from 'react';\nimport type { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\nimport Widget0 from \"../src/extensions/workspaces/sessions/(frontend)/tool/edit.mcp\";\n\nexport const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {\n \"@agimon-ai/po-edit/edit\": Widget0,\n};\n"],"mappings":";;;;AAGA,SAAS,cAAc,OAAyB;CAC9C,OACE,qBAAC,cAAD;EAAc,GAAI;EAAO,OAAM;EAA/B,UAAA,CACE,oBAAC,eAAD,EACE,QAAQ;GACN,CAAC,QAAQ,MAAM,KAAK,IAAI;GACxB,CAAC,iBAAiB,MAAM,KAAK,IAAI;GACjC,CAAC,WAAW,MAAM,QAAQ,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM,SAAS,KAAA,CAAS;EACnF,EACD,CAAA,GACD,oBAAC,eAAD,EAAe,QAAQ,MAAM,OAAS,CAAA,CAC1B;;AAElB;;;ACXA,MAAa,UAAqE,EAChF,2BDYa,gBAAgB,aCZFA,EAC7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.cjs","names":["Type","resolveInputPath","normalizeFileTag","withFileMutationQueue","access","constants","readFile","computeFileTag","decodeUtf8","stripBom","normalizeToLf","applyHashlineEdits","generateDiffString","generateUnifiedPatch","displayPath","writeFile","defineMcpTool","defineMcpPlugin","toolEdit"],"sources":["../../src/schemas/editTool.ts","../../src/services/editTool/index.ts","../../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp.ts","../../generated/mcp.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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type {\n DoomHeadlessExecutionContext,\n DoomHeadlessTool,\n DoomHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): DoomHeadlessTool<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.',\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: DoomHeadlessToolResult) => void) | undefined,\n context: DoomHeadlessExecutionContext,\n ) => executeHashlineEdit(params, context.cwd, signal),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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","import { defineMcpTool } from '@agimon-ai/po-core/mcpFacet';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineMcpTool(() => ({\n ...createHeadlessEditTool(),\n description:\n \"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.\",\n}));\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nconst withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({\n ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },\n});\n\nexport const mcp = defineMcpPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): DoomMcpSessionPlugin['tools'] { return [withWidget(\"@agimon-ai/po-edit/edit\", via({ name: 'edit' }, at(toolEdit, context)))]; },\n }) satisfies DoomMcpSessionPlugin,\n});\n\nexport default mcp;\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;;;AC2BD,SAAgB,yBAAoE;CAClF,OAAO;EACL,MAAM;EACN,OAAO;EACP,aACE;EACF,eAAe;EACf,kBAAkB,CAChB,qHACA,yGACF;EACA,YAAY;EACZ,eAAe;EACf,UACE,aACA,QACA,QACA,WACA,YACG,oBAAoB,QAAQ,QAAQ,KAAK,MAAM;CACtD;AACF;AAEA,SAAgB,iBAAiB,QAAuC;CACt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AAA,cAAAA,QAAqB;CAClC,GAAG,uBAAuB;CAC1B,aACE;AACJ,EAAE;;;ACFF,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAM,cAAiB,KAAa,UAAgB,UAAU,KAAA,IAAY,QAAS;CACjF,GAAG;CAAO,OAAO;EAAE,GAAI,MAA6B;GAAQ,cAAc;CAAI;AAChF;AAEA,MAAa,OAAA,GAAMC,4BAAAA,gBAAAA,CAAgB;CACjC,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,QAAuC;EAAE,OAAO,CAAC,WAAW,2BAA2B,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGC,kBAAU,OAAO,CAAC,CAAC,CAAC;CAAG,EAC7I;AACF,CAAC"}
1
+ {"version":3,"file":"mcp.cjs","names":["Type","resolveInputPath","normalizeFileTag","withFileMutationQueue","access","constants","readFile","computeFileTag","decodeUtf8","stripBom","normalizeToLf","applyHashlineEdits","generateDiffString","generateUnifiedPatch","displayPath","writeFile","defineMcpTool","defineMcpPlugin","toolEdit"],"sources":["../../src/schemas/editTool.ts","../../src/services/editTool/index.ts","../../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp.ts","../../generated/mcp.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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type { PoHeadlessExecutionContext, PoHeadlessTool, PoHeadlessToolResult } from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): 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.',\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),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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","import { defineMcpTool } from '@agimon-ai/po-core/mcpFacet';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineMcpTool(() => ({\n ...createHeadlessEditTool(),\n description:\n \"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.\",\n}));\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nconst withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({\n ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },\n});\n\nexport const mcp = defineMcpPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): PoMcpSessionPlugin['tools'] { return [withWidget(\"@agimon-ai/po-edit/edit\", via({ name: 'edit' }, at(toolEdit, context)))]; },\n }) satisfies PoMcpSessionPlugin,\n});\n\nexport default mcp;\n"],"mappings":";;;;;;;;;;;;AAEA,MAAa,sBAAsBA,QA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,UAAU,aAAa,EACrB,IAAI,QAAqC;EAAE,OAAO,CAAC,WAAW,2BAA2B,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGC,kBAAU,OAAO,CAAC,CAAC,CAAC;CAAG,EAC3I;AACF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  //#region generated/mcp.d.ts
2
- export declare const mcp: import("@agimon-ai/po-core/mcpFacet").DoomMcpPluginDefinition;
2
+ export declare const mcp: import("@agimon-ai/po-core/mcpFacet").PoMcpPluginDefinition;
3
3
  //#endregion
4
4
  export { mcp as default };
5
5
  //# sourceMappingURL=mcp.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.mjs","names":["toolEdit"],"sources":["../../src/schemas/editTool.ts","../../src/services/editTool/index.ts","../../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp.ts","../../generated/mcp.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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type {\n DoomHeadlessExecutionContext,\n DoomHeadlessTool,\n DoomHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): DoomHeadlessTool<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.',\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: DoomHeadlessToolResult) => void) | undefined,\n context: DoomHeadlessExecutionContext,\n ) => executeHashlineEdit(params, context.cwd, signal),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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","import { defineMcpTool } from '@agimon-ai/po-core/mcpFacet';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineMcpTool(() => ({\n ...createHeadlessEditTool(),\n description:\n \"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.\",\n}));\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nconst withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({\n ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },\n});\n\nexport const mcp = defineMcpPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): DoomMcpSessionPlugin['tools'] { return [withWidget(\"@agimon-ai/po-edit/edit\", via({ name: 'edit' }, at(toolEdit, context)))]; },\n }) satisfies DoomMcpSessionPlugin,\n});\n\nexport default mcp;\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,OAA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,GAAG,uBAAuB;CAC1B,aACE;AACJ,EAAE;;;ACFF,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAM,cAAiB,KAAa,UAAgB,UAAU,KAAA,IAAY,QAAS;CACjF,GAAG;CAAO,OAAO;EAAE,GAAI,MAA6B;GAAQ,cAAc;CAAI;AAChF;AAEA,MAAa,MAAM,gBAAgB;CACjC,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,QAAuC;EAAE,OAAO,CAAC,WAAW,2BAA2B,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGA,kBAAU,OAAO,CAAC,CAAC,CAAC;CAAG,EAC7I;AACF,CAAC"}
1
+ {"version":3,"file":"mcp.mjs","names":["toolEdit"],"sources":["../../src/schemas/editTool.ts","../../src/services/editTool/index.ts","../../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp.ts","../../generated/mcp.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 { constants } from 'node:fs';\nimport { access, readFile, writeFile } from 'node:fs/promises';\n\nimport type { PoHeadlessExecutionContext, PoHeadlessTool, PoHeadlessToolResult } from '@agimon-ai/po-core/headless';\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(): 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.',\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(params as EditParams, ctx.cwd, signal);\n },\n };\n}\n\nexport function createHeadlessEditTool(): 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.',\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),\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): Promise<{ content: [{ type: 'text'; text: string }]; details: EditToolDetails }> {\n const absolutePath = resolveInputPath(params.path, cwd);\n const expectedHash = normalizeFileTag(params.hash);\n return withFileMutationQueue(absolutePath, async () => {\n assertNotAborted(signal);\n await access(absolutePath, constants.R_OK | constants.W_OK);\n const beforeBytes = await readFile(absolutePath);\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 readFile(absolutePath);\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 await writeFile(absolutePath, output);\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","import { defineMcpTool } from '@agimon-ai/po-core/mcpFacet';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineMcpTool(() => ({\n ...createHeadlessEditTool(),\n description:\n \"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.\",\n}));\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.mcp';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nconst withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({\n ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },\n});\n\nexport const mcp = defineMcpPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): PoMcpSessionPlugin['tools'] { return [withWidget(\"@agimon-ai/po-edit/edit\", via({ name: 'edit' }, at(toolEdit, context)))]; },\n }) satisfies PoMcpSessionPlugin,\n});\n\nexport default mcp;\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,K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AM,GAAG,EAAE,IAAI;CACtE,OAAO,YAAY,KAAK,CAAC,IAAI,QAAQ,MAAM,IAAI;AACjD;;;ACrKA,IAAA,mBAAe,qBAAqB;CAClC,GAAG,uBAAuB;CAC1B,aACE;AACJ,EAAE;;;ACFF,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAM,cAAiB,KAAa,UAAgB,UAAU,KAAA,IAAY,QAAS;CACjF,GAAG;CAAO,OAAO;EAAE,GAAI,MAA6B;GAAQ,cAAc;CAAI;AAChF;AAEA,MAAa,MAAM,gBAAgB;CACjC,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,QAAqC;EAAE,OAAO,CAAC,WAAW,2BAA2B,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGA,kBAAU,OAAO,CAAC,CAAC,CAAC;CAAG,EAC3I;AACF,CAAC"}
@@ -0,0 +1,215 @@
1
+ import { defineNativePlugin, defineToolRenderer } from "@agimon-ai/po-core/native";
2
+ import { View } from "react-native-unistyles/components/native/View";
3
+ import { Text } from "react-native-unistyles/components/native/Text";
4
+ import { MessageItem, MessageItemBody, MessageItemHeader, MessageItemStatus, SyntaxLine, ToolPathLink, fontOf, toolTone, useSyntaxLines } from "@agimon-ai/po-native-components";
5
+ import { StyleSheet } from "react-native-unistyles";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
+ //#region src/extensions/workspaces/sessions/(frontend)/tool/_lib/editToolView.ts
8
+ /** Pi emits `+12 text`, `-12 text`, ` 12 text`, and a blank-numbered ` ... ` elision between hunks. */
9
+ const DIFF_ROW_PATTERN = /^([+\- ])( *\d*) (.*)$/u;
10
+ const CONTEXT_MARKER = " ";
11
+ /** What the edit call heading shows: the path and how many ranges the call touches. */
12
+ function editCallView(args) {
13
+ const count = Array.isArray(args.edits) ? args.edits.length : 0;
14
+ return {
15
+ path: typeof args.path === "string" ? args.path : "",
16
+ ranges: `${count} ${count === 1 ? "range" : "ranges"}`
17
+ };
18
+ }
19
+ function toDiffMarker(value) {
20
+ return value === "+" || value === "-" ? value : CONTEXT_MARKER;
21
+ }
22
+ /** Pi's display diff as rows; a line that is not a diff row reads as unnumbered context. */
23
+ function parseDiffRows(diff) {
24
+ return diff.split("\n").map((line) => {
25
+ const expanded = line.replaceAll(" ", " ");
26
+ const match = DIFF_ROW_PATTERN.exec(expanded);
27
+ if (!match) return {
28
+ marker: CONTEXT_MARKER,
29
+ lineNumber: "",
30
+ content: expanded
31
+ };
32
+ return {
33
+ marker: toDiffMarker(match[1]),
34
+ lineNumber: (match[2] ?? "").trim(),
35
+ content: match[3] ?? ""
36
+ };
37
+ });
38
+ }
39
+ /** The diff a successful edit carries in its details; undefined when the details never arrived. */
40
+ function editResultView(result) {
41
+ const details = result?.details;
42
+ if (typeof details !== "object" || details === null) return void 0;
43
+ const diff = details.diff;
44
+ if (typeof diff !== "string" || diff.length === 0) return void 0;
45
+ const rows = parseDiffRows(diff);
46
+ return {
47
+ rows,
48
+ gutter: rows.reduce((widest, row) => Math.max(widest, row.lineNumber.length), 1)
49
+ };
50
+ }
51
+ /** The result's text lines, for the error case where the diff never happened. */
52
+ function resultTextLines(result, output) {
53
+ const lines = (result === null ? output : result.content.flatMap((block) => {
54
+ const record = typeof block === "object" && block !== null ? block : {};
55
+ return record.type === "text" && typeof record.text === "string" ? [record.text] : [];
56
+ }).join("\n")).replaceAll(" ", " ").replaceAll("\r\n", "\n").split("\n");
57
+ while (lines.at(-1) === "") lines.pop();
58
+ return lines;
59
+ }
60
+ //#endregion
61
+ //#region src/extensions/workspaces/sessions/(frontend)/tool/_components/EditToolMessage.native.tsx
62
+ /**
63
+ * The banded rows and the grammar over them, as the web's DiffRows: parsed as
64
+ * one document, so a replaced line is seen twice and may colour oddly, and the
65
+ * `+`/`-` wash stays underneath so what changed is still legible.
66
+ */
67
+ function DiffRows({ rows, gutter, path }) {
68
+ const spans = useSyntaxLines(rows.map((row) => row.content).join("\n"), { path });
69
+ return /* @__PURE__ */ jsx(View, { children: rows.map((row, index) => /* @__PURE__ */ jsxs(View, {
70
+ style: styles.row(row.marker),
71
+ children: [
72
+ /* @__PURE__ */ jsx(Text, {
73
+ style: [styles.mono, styles.gutter],
74
+ children: row.lineNumber.padStart(gutter)
75
+ }),
76
+ /* @__PURE__ */ jsx(Text, {
77
+ style: [styles.mono, styles.ink(row.marker)],
78
+ children: row.marker
79
+ }),
80
+ /* @__PURE__ */ jsx(SyntaxLine, {
81
+ selectable: true,
82
+ spans: spans?.[index],
83
+ text: row.content,
84
+ style: [
85
+ styles.mono,
86
+ styles.content,
87
+ styles.ink(row.marker)
88
+ ]
89
+ })
90
+ ]
91
+ }, `${String(index)}-${row.lineNumber}`)) });
92
+ }
93
+ /**
94
+ * The edit tool's timeline item on native, as the web's EditToolMessage:
95
+ * `path · N ranges` in the header, the display diff banded by row in the body,
96
+ * and the tool's message in red when the edit failed.
97
+ */
98
+ function EditToolMessage({ args, result, output, running, isError, fileTabFor, openTransientTab }) {
99
+ const call = editCallView(args);
100
+ const view = result === null || isError ? void 0 : editResultView(result);
101
+ const tab = fileTabFor(call.path);
102
+ return /* @__PURE__ */ jsx(MessageItem, {
103
+ tone: toolTone({
104
+ running,
105
+ isError
106
+ }),
107
+ expandable: true,
108
+ children: ({ expanded }) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(MessageItemHeader, {
109
+ title: "edit",
110
+ children: /* @__PURE__ */ jsxs(View, {
111
+ testID: "tool-call-edit",
112
+ style: styles.summary,
113
+ children: [/* @__PURE__ */ jsx(ToolPathLink, {
114
+ path: call.path,
115
+ ...tab === void 0 ? {} : { onOpen: () => openTransientTab(tab) }
116
+ }), /* @__PURE__ */ jsxs(Text, {
117
+ numberOfLines: 1,
118
+ style: styles.detail,
119
+ children: ["· ", call.ranges]
120
+ })]
121
+ })
122
+ }), !expanded ? null : isError ? /* @__PURE__ */ jsxs(MessageItemBody, {
123
+ testID: "tool-result-edit",
124
+ children: [/* @__PURE__ */ jsx(MessageItemStatus, {
125
+ tone: "error",
126
+ children: "failed"
127
+ }), resultTextLines(result, output).map((line, index) => /* @__PURE__ */ jsx(Text, {
128
+ selectable: true,
129
+ style: styles.error,
130
+ children: line
131
+ }, `${String(index)}-${line}`))]
132
+ }) : view === void 0 ? running ? /* @__PURE__ */ jsx(MessageItemBody, {
133
+ testID: "tool-result-edit",
134
+ children: /* @__PURE__ */ jsx(MessageItemStatus, {
135
+ tone: "running",
136
+ children: "running"
137
+ })
138
+ }) : null : /* @__PURE__ */ jsx(MessageItemBody, {
139
+ testID: "tool-result-edit",
140
+ children: /* @__PURE__ */ jsx(DiffRows, {
141
+ rows: view.rows,
142
+ gutter: view.gutter,
143
+ path: call.path
144
+ })
145
+ })] })
146
+ });
147
+ }
148
+ const styles = StyleSheet.create((theme) => ({
149
+ summary: {
150
+ flex: 1,
151
+ flexDirection: "row",
152
+ alignItems: "center",
153
+ gap: theme.spacing(2),
154
+ minWidth: 0,
155
+ uni__dependencies: [0]
156
+ },
157
+ detail: {
158
+ flexShrink: 0,
159
+ color: theme.colors.faint,
160
+ fontFamily: fontOf(theme.fontFamily.sans),
161
+ fontSize: theme.fontSize.base,
162
+ lineHeight: theme.lineHeight.base,
163
+ uni__dependencies: [0]
164
+ },
165
+ error: {
166
+ color: theme.colors.red,
167
+ fontFamily: fontOf(theme.fontFamily.sans),
168
+ fontSize: theme.fontSize.base,
169
+ lineHeight: theme.lineHeight.base,
170
+ uni__dependencies: [0]
171
+ },
172
+ row: (marker) => ({
173
+ flexDirection: "row",
174
+ gap: theme.spacing(2),
175
+ backgroundColor: marker === "+" ? theme.colors["tint-green"] : marker === "-" ? theme.colors["tint-red"] : void 0,
176
+ uni__dependencies: [0]
177
+ }),
178
+ mono: {
179
+ fontFamily: fontOf(theme.fontFamily.mono),
180
+ fontSize: theme.fontSize.sm,
181
+ lineHeight: theme.lineHeightRelaxed.sm,
182
+ uni__dependencies: [0]
183
+ },
184
+ gutter: {
185
+ color: theme.colors.faint,
186
+ uni__dependencies: [0]
187
+ },
188
+ ink: (marker) => ({
189
+ color: marker === "+" ? theme.colors.green : marker === "-" ? theme.colors.red : theme.colors.dim,
190
+ uni__dependencies: [0]
191
+ }),
192
+ content: {
193
+ flex: 1,
194
+ minWidth: 0
195
+ }
196
+ }));
197
+ //#endregion
198
+ //#region src/extensions/workspaces/sessions/(frontend)/tool/edit.native.tsx
199
+ var edit_native_default = defineToolRenderer({ message: EditToolMessage });
200
+ //#endregion
201
+ //#region generated/native.ts
202
+ const via = (identity, value) => value === void 0 ? void 0 : {
203
+ ...identity,
204
+ ...value
205
+ };
206
+ const nativePlugin = defineNativePlugin({
207
+ id: "edit",
208
+ session: { get toolRenderers() {
209
+ return [via({ tools: ["edit"] }, edit_native_default)];
210
+ } }
211
+ });
212
+ //#endregion
213
+ export { nativePlugin };
214
+
215
+ //# sourceMappingURL=native.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native.mjs","names":["ToolMessageRenderProps","fontOf","MessageItem","MessageItemBody","MessageItemHeader","MessageItemStatus","SyntaxLine","ToolPathLink","toolTone","useSyntaxLines","PoNativeTheme","StyleSheet","DiffMarker","DiffRow","editCallView","editResultView","resultTextLines","DiffRows","rows","gutter","path","spans","map","row","content","join","index","String","lineNumber","styles","marker","mono","padStart","ink","EditToolMessage","args","result","output","running","isError","fileTabFor","openTransientTab","call","view","undefined","tab","expanded","summary","onOpen","detail","ranges","line","error","create","theme","flex","flexDirection","alignItems","gap","spacing","minWidth","uni__dependencies","flexShrink","color","colors","faint","fontFamily","sans","fontSize","base","lineHeight","red","backgroundColor","sm","lineHeightRelaxed","green","dim","toolEdit"],"sources":["../../src/extensions/workspaces/sessions/(frontend)/tool/_lib/editToolView.ts","../../src/extensions/workspaces/sessions/(frontend)/tool/_components/EditToolMessage.native.tsx","../../src/extensions/workspaces/sessions/(frontend)/tool/edit.native.tsx","../../generated/native.ts"],"sourcesContent":["import type { ToolResultView } from '@agimon-ai/po-core/web';\n\n/** Pi emits `+12 text`, `-12 text`, ` 12 text`, and a blank-numbered ` ... ` elision between hunks. */\nconst DIFF_ROW_PATTERN = /^([+\\- ])( *\\d*) (.*)$/u;\nconst CONTEXT_MARKER = ' ';\n\nexport type DiffMarker = '+' | '-' | typeof CONTEXT_MARKER;\n\nexport interface DiffRow {\n readonly marker: DiffMarker;\n readonly lineNumber: string;\n readonly content: string;\n}\n\nexport interface EditCallView {\n readonly path: string;\n /** `N range` or `N ranges`, the count the TUI's call heading shows. */\n readonly ranges: string;\n}\n\nexport interface EditResultView {\n readonly rows: readonly DiffRow[];\n /** Widest line number among the rows, in characters, sizing the gutter. */\n readonly gutter: number;\n}\n\n/** What the edit call heading shows: the path and how many ranges the call touches. */\nexport function editCallView(args: Readonly<Record<string, unknown>>): EditCallView {\n const count = Array.isArray(args.edits) ? args.edits.length : 0;\n return {\n path: typeof args.path === 'string' ? args.path : '',\n ranges: `${count} ${count === 1 ? 'range' : 'ranges'}`,\n };\n}\n\nfunction toDiffMarker(value: string | undefined): DiffMarker {\n return value === '+' || value === '-' ? value : CONTEXT_MARKER;\n}\n\n/** Pi's display diff as rows; a line that is not a diff row reads as unnumbered context. */\nexport function parseDiffRows(diff: string): DiffRow[] {\n return diff.split('\\n').map((line) => {\n const expanded = line.replaceAll('\\t', ' ');\n const match = DIFF_ROW_PATTERN.exec(expanded);\n if (!match) return { marker: CONTEXT_MARKER, lineNumber: '', content: expanded };\n return { marker: toDiffMarker(match[1]), lineNumber: (match[2] ?? '').trim(), content: match[3] ?? '' };\n });\n}\n\n/** The diff a successful edit carries in its details; undefined when the details never arrived. */\nexport function editResultView(result: ToolResultView | null): EditResultView | undefined {\n const details = result?.details;\n if (typeof details !== 'object' || details === null) return undefined;\n const diff = (details as { diff?: unknown }).diff;\n if (typeof diff !== 'string' || diff.length === 0) return undefined;\n const rows = parseDiffRows(diff);\n return { rows, gutter: rows.reduce((widest, row) => Math.max(widest, row.lineNumber.length), 1) };\n}\n\n/** The result's text lines, for the error case where the diff never happened. */\nexport function resultTextLines(result: ToolResultView | null, output: string): string[] {\n const text =\n result === null\n ? output\n : result.content\n .flatMap((block) => {\n const record =\n typeof block === 'object' && block !== null ? (block as { type?: unknown; text?: unknown }) : {};\n return record.type === 'text' && typeof record.text === 'string' ? [record.text] : [];\n })\n .join('\\n');\n const lines = text.replaceAll('\\t', ' ').replaceAll('\\r\\n', '\\n').split('\\n');\n while (lines.at(-1) === '') lines.pop();\n return lines;\n}\n","import type { ToolMessageRenderProps } from '@agimon-ai/po-core/native';\nimport {\n fontOf,\n MessageItem,\n MessageItemBody,\n MessageItemHeader,\n MessageItemStatus,\n SyntaxLine,\n ToolPathLink,\n toolTone,\n useSyntaxLines,\n} from '@agimon-ai/po-native-components';\nimport type { PoNativeTheme } from '@agimon-ai/po-web-components/nativeTheme';\nimport { Text, View } from 'react-native';\nimport { StyleSheet } from 'react-native-unistyles';\n\nimport { type DiffMarker, type DiffRow, editCallView, editResultView, resultTextLines } from '../_lib/editToolView';\n\n/**\n * The banded rows and the grammar over them, as the web's DiffRows: parsed as\n * one document, so a replaced line is seen twice and may colour oddly, and the\n * `+`/`-` wash stays underneath so what changed is still legible.\n */\nfunction DiffRows({ rows, gutter, path }: { rows: readonly DiffRow[]; gutter: number; path: string }) {\n const spans = useSyntaxLines(rows.map((row) => row.content).join('\\n'), { path });\n return (\n <View>\n {rows.map((row, index) => (\n <View key={`${String(index)}-${row.lineNumber}`} style={styles.row(row.marker)}>\n <Text style={[styles.mono, styles.gutter]}>{row.lineNumber.padStart(gutter)}</Text>\n <Text style={[styles.mono, styles.ink(row.marker)]}>{row.marker}</Text>\n <SyntaxLine\n selectable\n spans={spans?.[index]}\n text={row.content}\n style={[styles.mono, styles.content, styles.ink(row.marker)]}\n />\n </View>\n ))}\n </View>\n );\n}\n\n/**\n * The edit tool's timeline item on native, as the web's EditToolMessage:\n * `path · N ranges` in the header, the display diff banded by row in the body,\n * and the tool's message in red when the edit failed.\n */\nexport function EditToolMessage({\n args,\n result,\n output,\n running,\n isError,\n fileTabFor,\n openTransientTab,\n}: ToolMessageRenderProps) {\n const call = editCallView(args);\n const view = result === null || isError ? undefined : editResultView(result);\n const tab = fileTabFor(call.path);\n return (\n <MessageItem tone={toolTone({ running, isError })} expandable>\n {({ expanded }) => (\n <>\n <MessageItemHeader title=\"edit\">\n <View testID=\"tool-call-edit\" style={styles.summary}>\n <ToolPathLink path={call.path} {...(tab === undefined ? {} : { onOpen: () => openTransientTab(tab) })} />\n <Text numberOfLines={1} style={styles.detail}>\n · {call.ranges}\n </Text>\n </View>\n </MessageItemHeader>\n {!expanded ? null : isError ? (\n <MessageItemBody testID=\"tool-result-edit\">\n <MessageItemStatus tone=\"error\">failed</MessageItemStatus>\n {resultTextLines(result, output).map((line, index) => (\n <Text key={`${String(index)}-${line}`} selectable style={styles.error}>\n {line}\n </Text>\n ))}\n </MessageItemBody>\n ) : view === undefined ? (\n running ? (\n <MessageItemBody testID=\"tool-result-edit\">\n <MessageItemStatus tone=\"running\">running</MessageItemStatus>\n </MessageItemBody>\n ) : null\n ) : (\n <MessageItemBody testID=\"tool-result-edit\">\n <DiffRows rows={view.rows} gutter={view.gutter} path={call.path} />\n </MessageItemBody>\n )}\n </>\n )}\n </MessageItem>\n );\n}\n\n// Po carries a diff on the background the way Magit does: a green wash on\n// added rows, a red wash on removed ones, and the foreground left to the text.\nconst styles = StyleSheet.create((theme: PoNativeTheme) => ({\n summary: { flex: 1, flexDirection: 'row', alignItems: 'center', gap: theme.spacing(2), minWidth: 0 },\n detail: {\n flexShrink: 0,\n color: theme.colors.faint,\n fontFamily: fontOf(theme.fontFamily.sans),\n fontSize: theme.fontSize.base,\n lineHeight: theme.lineHeight.base,\n },\n error: {\n color: theme.colors.red,\n fontFamily: fontOf(theme.fontFamily.sans),\n fontSize: theme.fontSize.base,\n lineHeight: theme.lineHeight.base,\n },\n row: (marker: DiffMarker) => ({\n flexDirection: 'row',\n gap: theme.spacing(2),\n backgroundColor:\n marker === '+' ? theme.colors['tint-green'] : marker === '-' ? theme.colors['tint-red'] : undefined,\n }),\n mono: {\n fontFamily: fontOf(theme.fontFamily.mono),\n fontSize: theme.fontSize.sm,\n lineHeight: theme.lineHeightRelaxed.sm,\n },\n gutter: { color: theme.colors.faint },\n ink: (marker: DiffMarker) => ({\n color: marker === '+' ? theme.colors.green : marker === '-' ? theme.colors.red : theme.colors.dim,\n }),\n content: { flex: 1, minWidth: 0 },\n}));\n","import { defineToolRenderer } from '@agimon-ai/po-core/native';\n\nimport { EditToolMessage } from './_components/EditToolMessage.native';\n\nexport default defineToolRenderer({ message: EditToolMessage });\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineNativePlugin, type WebPluginContributions } from '@agimon-ai/po-core/native';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(frontend)/tool/edit.native';\n\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const nativePlugin = defineNativePlugin({\n id: 'edit',\n session: {\n get toolRenderers(): WebPluginContributions['toolRenderers'] { return [via({ tools: ['edit'] }, toolEdit)]; },\n },\n});\n"],"mappings":";;;;;;;;AAGA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;AAuBvB,SAAgB,aAAa,MAAuD;CAClF,MAAM,QAAQ,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,MAAM,SAAS;CAC9D,OAAO;EACL,MAAM,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;EAClD,QAAQ,GAAG,MAAM,GAAG,UAAU,IAAI,UAAU;CAC9C;AACF;AAEA,SAAS,aAAa,OAAuC;CAC3D,OAAO,UAAU,OAAO,UAAU,MAAM,QAAQ;AAClD;;AAGA,SAAgB,cAAc,MAAyB;CACrD,OAAO,KAAK,MAAM,IAAI,CAAC,CAA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
6
- let _agimon_ai_po_core_serverFacet = require("@agimon-ai/po-core/serverFacet");
6
+ let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
7
7
  //#region src/extensions/workspaces/sessions/(backend)/tool/edit.server.ts
8
8
  var edit_server_default = (0, require("@agimon-ai/po-core/extensionFile").defineServerTool)(require_editTool.createHeadlessEditTool);
9
9
  //#endregion
@@ -13,14 +13,14 @@ const via = (identity, value) => value === void 0 ? void 0 : {
13
13
  ...identity,
14
14
  ...value
15
15
  };
16
- const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
16
+ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
17
17
  name: "@agimon-ai/po-edit",
18
18
  session: (context) => ({ get tools() {
19
19
  return [via({ name: "edit" }, at(edit_server_default, context))];
20
20
  } })
21
21
  });
22
22
  //#endregion
23
- exports.default = facet;
24
- exports.facet = facet;
23
+ exports.default = serverPlugin;
24
+ exports.serverPlugin = serverPlugin;
25
25
 
26
26
  //# sourceMappingURL=server.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.cjs","names":["defineServerTool","createHeadlessEditTool","defineServerPlugin","toolEdit"],"sources":["../../src/extensions/workspaces/sessions/(backend)/tool/edit.server.ts","../../generated/server.ts"],"sourcesContent":["import { defineServerTool } from '@agimon-ai/po-core/extensionFile';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineServerTool(createHeadlessEditTool);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type DoomServerSessionPlugin } from '@agimon-ai/po-core/serverFacet';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const facet = defineServerPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): DoomServerSessionPlugin['tools'] { return [via({ name: 'edit' }, at(toolEdit, context))]; },\n }),\n});\n\nexport default facet;\n"],"mappings":";;;;;;;AAIA,IAAA,uBAAA,6CAAeA,CAAAA,CAAAA,iBAAAA,CAAiBC,iBAAAA,sBAAsB;;;ACEtD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,SAAA,GAAQC,+BAAAA,mBAAAA,CAAmB;CACtC,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,QAA0C;EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGC,qBAAU,OAAO,CAAC,CAAC;CAAG,EACzG;AACF,CAAC"}
1
+ {"version":3,"file":"server.cjs","names":["defineServerTool","createHeadlessEditTool","defineServerPlugin","toolEdit"],"sources":["../../src/extensions/workspaces/sessions/(backend)/tool/edit.server.ts","../../generated/server.ts"],"sourcesContent":["import { defineServerTool } from '@agimon-ai/po-core/extensionFile';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineServerTool(createHeadlessEditTool);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'edit' }, at(toolEdit, context))]; },\n }),\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;AAIA,IAAA,uBAAA,6CAAeA,CAAAA,CAAAA,iBAAAA,CAAiBC,iBAAAA,sBAAsB;;;ACEtD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,gBAAA,GAAeC,gCAAAA,mBAAAA,CAAmB;CAC7C,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,QAAwC;EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGC,qBAAU,OAAO,CAAC,CAAC;CAAG,EACvG;AACF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  //#region generated/server.d.ts
2
- export declare const facet: import("@agimon-ai/po-core/serverFacet").DoomServerFacet;
2
+ export declare const serverPlugin: import("@agimon-ai/po-core/serverPlugin").PoServerPlugin;
3
3
  //#endregion
4
- export { facet as default };
4
+ export { serverPlugin as default };
5
5
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../../generated/server.ts"],"mappings":";qBAWa,gDAAK"}
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../../generated/server.ts"],"mappings":";qBAWa,wDAAY"}
@@ -1,5 +1,5 @@
1
1
  import { n as createHeadlessEditTool } from "../editTool--RaZ-yPH.mjs";
2
- import { defineServerPlugin } from "@agimon-ai/po-core/serverFacet";
2
+ import { defineServerPlugin } from "@agimon-ai/po-core/serverPlugin";
3
3
  import { defineServerTool } from "@agimon-ai/po-core/extensionFile";
4
4
  //#region src/extensions/workspaces/sessions/(backend)/tool/edit.server.ts
5
5
  var edit_server_default = defineServerTool(createHeadlessEditTool);
@@ -10,13 +10,13 @@ const via = (identity, value) => value === void 0 ? void 0 : {
10
10
  ...identity,
11
11
  ...value
12
12
  };
13
- const facet = defineServerPlugin({
13
+ const serverPlugin = defineServerPlugin({
14
14
  name: "@agimon-ai/po-edit",
15
15
  session: (context) => ({ get tools() {
16
16
  return [via({ name: "edit" }, at(edit_server_default, context))];
17
17
  } })
18
18
  });
19
19
  //#endregion
20
- export { facet as default, facet };
20
+ export { serverPlugin as default, serverPlugin };
21
21
 
22
22
  //# sourceMappingURL=server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":["toolEdit"],"sources":["../../src/extensions/workspaces/sessions/(backend)/tool/edit.server.ts","../../generated/server.ts"],"sourcesContent":["import { defineServerTool } from '@agimon-ai/po-core/extensionFile';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineServerTool(createHeadlessEditTool);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type DoomServerSessionPlugin } from '@agimon-ai/po-core/serverFacet';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const facet = defineServerPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): DoomServerSessionPlugin['tools'] { return [via({ name: 'edit' }, at(toolEdit, context))]; },\n }),\n});\n\nexport default facet;\n"],"mappings":";;;;AAIA,IAAA,sBAAe,iBAAiB,sBAAsB;;;ACEtD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,QAAQ,mBAAmB;CACtC,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,QAA0C;EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGA,qBAAU,OAAO,CAAC,CAAC;CAAG,EACzG;AACF,CAAC"}
1
+ {"version":3,"file":"server.mjs","names":["toolEdit"],"sources":["../../src/extensions/workspaces/sessions/(backend)/tool/edit.server.ts","../../generated/server.ts"],"sourcesContent":["import { defineServerTool } from '@agimon-ai/po-core/extensionFile';\n\nimport { createHeadlessEditTool } from '../../../../../services/editTool';\n\nexport default defineServerTool(createHeadlessEditTool);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(backend)/tool/edit.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-edit',\n session: (context) => ({\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'edit' }, at(toolEdit, context))]; },\n }),\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;AAIA,IAAA,sBAAe,iBAAiB,sBAAsB;;;ACEtD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,eAAe,mBAAmB;CAC7C,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,QAAwC;EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGA,qBAAU,OAAO,CAAC,CAAC;CAAG,EACvG;AACF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { defineToolRenderer, defineWebPlugin } from "@agimon-ai/po-core/web";
2
- import { MessageItem, MessageItemBody, MessageItemHeader, MessageItemStatus, SyntaxLine, ToolPathLink, collapseLines, toolTone, useSyntaxLines } from "@agimon-ai/po-web-components";
2
+ import { MessageItem, MessageItemBody, MessageItemHeader, MessageItemStatus, SyntaxLine, ToolPathLink, toolTone, useSyntaxLines } from "@agimon-ai/po-web-components";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region src/extensions/workspaces/sessions/(frontend)/tool/_lib/editToolView.ts
5
5
  /** Pi emits `+12 text`, `-12 text`, ` 12 text`, and a blank-numbered ` ... ` elision between hunks. */
@@ -56,12 +56,10 @@ function resultTextLines(result, output) {
56
56
  }
57
57
  //#endregion
58
58
  //#region src/extensions/workspaces/sessions/(frontend)/tool/_components/EditToolMessage.tsx
59
- /** Diff rows shown until the item expands; about what the old scroll box held. */
60
- const COLLAPSED_ROWS = 24;
61
59
  const ROW_TONE = {
62
- "+": "bg-doom-tint-green text-doom-green",
63
- "-": "bg-doom-tint-red text-doom-red",
64
- " ": "text-doom-dim"
60
+ "+": "bg-po-tint-green text-po-green",
61
+ "-": "bg-po-tint-red text-po-red",
62
+ " ": "text-po-dim"
65
63
  };
66
64
  /**
67
65
  * The banded rows, and the grammar over them.
@@ -79,7 +77,7 @@ function DiffRows({ rows, gutter, path }) {
79
77
  className: `flex gap-2 ${ROW_TONE[row.marker]}`,
80
78
  children: [
81
79
  /* @__PURE__ */ jsx("span", {
82
- className: "shrink-0 text-right text-doom-faint",
80
+ className: "shrink-0 text-right text-po-faint",
83
81
  style: { width: `${String(gutter)}ch` },
84
82
  children: row.lineNumber
85
83
  }),
@@ -110,7 +108,7 @@ function EditToolMessage({ args, result, output, running, isError, fileTabFor, o
110
108
  running,
111
109
  isError
112
110
  }),
113
- expandable: view !== void 0 && view.rows.length > COLLAPSED_ROWS,
111
+ expandable: true,
114
112
  children: ({ expanded }) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(MessageItemHeader, {
115
113
  title: "edit",
116
114
  children: /* @__PURE__ */ jsxs("span", {
@@ -120,18 +118,18 @@ function EditToolMessage({ args, result, output, running, isError, fileTabFor, o
120
118
  path: call.path,
121
119
  ...tab === void 0 ? {} : { onOpen: () => openTransientTab(tab) }
122
120
  }), /* @__PURE__ */ jsxs("span", {
123
- className: "shrink-0 text-doom-faint",
121
+ className: "shrink-0 text-po-faint",
124
122
  children: ["· ", call.ranges]
125
123
  })]
126
124
  })
127
- }), isError ? /* @__PURE__ */ jsxs(MessageItemBody, {
125
+ }), !expanded ? null : isError ? /* @__PURE__ */ jsxs(MessageItemBody, {
128
126
  "data-testid": "tool-result-edit",
129
127
  className: "flex flex-col",
130
128
  children: [/* @__PURE__ */ jsx(MessageItemStatus, {
131
129
  tone: "error",
132
130
  children: "failed"
133
131
  }), resultTextLines(result, output).map((line, index) => /* @__PURE__ */ jsx("span", {
134
- className: "whitespace-pre-wrap break-words text-doom-red",
132
+ className: "whitespace-pre-wrap break-words text-po-red",
135
133
  children: line
136
134
  }, `${String(index)}-${line}`))]
137
135
  }) : view === void 0 ? running ? /* @__PURE__ */ jsx(MessageItemBody, {
@@ -140,22 +138,15 @@ function EditToolMessage({ args, result, output, running, isError, fileTabFor, o
140
138
  tone: "running",
141
139
  children: "running"
142
140
  })
143
- }) : null : (() => {
144
- const { shown, hidden } = collapseLines(view.rows, COLLAPSED_ROWS, expanded);
145
- return /* @__PURE__ */ jsxs(MessageItemBody, {
146
- "data-testid": "tool-result-edit",
147
- className: "flex flex-col font-mono",
148
- children: [/* @__PURE__ */ jsx(DiffRows, {
149
- rows: shown,
150
- gutter: view.gutter,
151
- path: call.path
152
- }), hidden > 0 ? /* @__PURE__ */ jsxs(MessageItemStatus, {
153
- expands: true,
154
- className: "pt-1",
155
- children: [hidden, " more rows"]
156
- }) : null]
157
- });
158
- })()] })
141
+ }) : null : /* @__PURE__ */ jsx(MessageItemBody, {
142
+ "data-testid": "tool-result-edit",
143
+ className: "flex flex-col font-mono",
144
+ children: /* @__PURE__ */ jsx(DiffRows, {
145
+ rows: view.rows,
146
+ gutter: view.gutter,
147
+ path: call.path
148
+ })
149
+ })] })
159
150
  });
160
151
  }
161
152
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"web.mjs","names":["toolEdit"],"sources":["../../src/extensions/workspaces/sessions/(frontend)/tool/_lib/editToolView.ts","../../src/extensions/workspaces/sessions/(frontend)/tool/_components/EditToolMessage.tsx","../../src/extensions/workspaces/sessions/(frontend)/tool/edit.web.tsx","../../generated/web.ts"],"sourcesContent":["import type { ToolResultView } from '@agimon-ai/po-core/web';\n\n/** Pi emits `+12 text`, `-12 text`, ` 12 text`, and a blank-numbered ` ... ` elision between hunks. */\nconst DIFF_ROW_PATTERN = /^([+\\- ])( *\\d*) (.*)$/u;\nconst CONTEXT_MARKER = ' ';\n\nexport type DiffMarker = '+' | '-' | typeof CONTEXT_MARKER;\n\nexport interface DiffRow {\n readonly marker: DiffMarker;\n readonly lineNumber: string;\n readonly content: string;\n}\n\nexport interface EditCallView {\n readonly path: string;\n /** `N range` or `N ranges`, the count the TUI's call heading shows. */\n readonly ranges: string;\n}\n\nexport interface EditResultView {\n readonly rows: readonly DiffRow[];\n /** Widest line number among the rows, in characters, sizing the gutter. */\n readonly gutter: number;\n}\n\n/** What the edit call heading shows: the path and how many ranges the call touches. */\nexport function editCallView(args: Readonly<Record<string, unknown>>): EditCallView {\n const count = Array.isArray(args.edits) ? args.edits.length : 0;\n return {\n path: typeof args.path === 'string' ? args.path : '',\n ranges: `${count} ${count === 1 ? 'range' : 'ranges'}`,\n };\n}\n\nfunction toDiffMarker(value: string | undefined): DiffMarker {\n return value === '+' || value === '-' ? value : CONTEXT_MARKER;\n}\n\n/** Pi's display diff as rows; a line that is not a diff row reads as unnumbered context. */\nexport function parseDiffRows(diff: string): DiffRow[] {\n return diff.split('\\n').map((line) => {\n const expanded = line.replaceAll('\\t', ' ');\n const match = DIFF_ROW_PATTERN.exec(expanded);\n if (!match) return { marker: CONTEXT_MARKER, lineNumber: '', content: expanded };\n return { marker: toDiffMarker(match[1]), lineNumber: (match[2] ?? '').trim(), content: match[3] ?? '' };\n });\n}\n\n/** The diff a successful edit carries in its details; undefined when the details never arrived. */\nexport function editResultView(result: ToolResultView | null): EditResultView | undefined {\n const details = result?.details;\n if (typeof details !== 'object' || details === null) return undefined;\n const diff = (details as { diff?: unknown }).diff;\n if (typeof diff !== 'string' || diff.length === 0) return undefined;\n const rows = parseDiffRows(diff);\n return { rows, gutter: rows.reduce((widest, row) => Math.max(widest, row.lineNumber.length), 1) };\n}\n\n/** The result's text lines, for the error case where the diff never happened. */\nexport function resultTextLines(result: ToolResultView | null, output: string): string[] {\n const text =\n result === null\n ? output\n : result.content\n .flatMap((block) => {\n const record =\n typeof block === 'object' && block !== null ? (block as { type?: unknown; text?: unknown }) : {};\n return record.type === 'text' && typeof record.text === 'string' ? [record.text] : [];\n })\n .join('\\n');\n const lines = text.replaceAll('\\t', ' ').replaceAll('\\r\\n', '\\n').split('\\n');\n while (lines.at(-1) === '') lines.pop();\n return lines;\n}\n","import type { ToolMessageRenderProps } from '@agimon-ai/po-core/web';\nimport {\n collapseLines,\n MessageItem,\n MessageItemBody,\n MessageItemHeader,\n MessageItemStatus,\n SyntaxLine,\n ToolPathLink,\n toolTone,\n useSyntaxLines,\n} from '@agimon-ai/po-web-components';\n\nimport { type DiffRow, editCallView, editResultView, resultTextLines } from '../_lib/editToolView';\n\n/** Diff rows shown until the item expands; about what the old scroll box held. */\nconst COLLAPSED_ROWS = 24;\n\n// Doom carries a diff on the background the way Magit does: a green wash on\n// added rows, a red wash on removed ones, and the foreground left to the text.\nconst ROW_TONE: Readonly<Record<DiffRow['marker'], string>> = {\n '+': 'bg-doom-tint-green text-doom-green',\n '-': 'bg-doom-tint-red text-doom-red',\n ' ': 'text-doom-dim',\n};\n\n/**\n * The banded rows, and the grammar over them.\n *\n * Its own component because the colours come from a hook, and the body that\n * renders these rows is chosen inside a render prop. The rows are parsed as\n * one document: a diff is not a file, so a replaced line is seen twice and a\n * split string can colour oddly, which costs a token here and there and never\n * costs the reader the text. The `+` and `-` wash stays underneath, so what\n * changed is still legible when the grammar has coloured the foreground.\n */\nfunction DiffRows({ rows, gutter, path }: { rows: readonly DiffRow[]; gutter: number; path: string }) {\n const spans = useSyntaxLines(rows.map((row) => row.content).join('\\n'), { path });\n return (\n <>\n {rows.map((row, index) => (\n <span key={`${String(index)}-${row.lineNumber}`} className={`flex gap-2 ${ROW_TONE[row.marker]}`}>\n <span className=\"shrink-0 text-right text-doom-faint\" style={{ width: `${String(gutter)}ch` }}>\n {row.lineNumber}\n </span>\n <span className=\"w-2 shrink-0\">{row.marker === ' ' ? '' : row.marker}</span>\n <SyntaxLine spans={spans?.[index]} text={row.content} className=\"min-w-0 whitespace-pre-wrap break-words\" />\n </span>\n ))}\n </>\n );\n}\n\n/**\n * The edit tool's timeline item: `path · N ranges` in the header; the display\n * diff from the result's details, banded by row, in the body. A successful\n * edit whose details never arrived shows nothing, and a failed one shows the\n * tool's message in red.\n */\nexport function EditToolMessage({\n args,\n result,\n output,\n running,\n isError,\n fileTabFor,\n openTransientTab,\n}: ToolMessageRenderProps) {\n const call = editCallView(args);\n const view = result === null || isError ? undefined : editResultView(result);\n // The file this edit lands in, opened from the header rather than found\n // again in a file list; plain text when nothing installed can show it.\n const tab = fileTabFor(call.path);\n return (\n <MessageItem\n tone={toolTone({ running, isError })}\n expandable={view !== undefined && view.rows.length > COLLAPSED_ROWS}\n >\n {({ expanded }) => (\n <>\n <MessageItemHeader title=\"edit\">\n <span data-testid=\"tool-call-edit\" className=\"flex min-w-0 flex-1 items-center gap-2\">\n <ToolPathLink path={call.path} {...(tab === undefined ? {} : { onOpen: () => openTransientTab(tab) })} />\n <span className=\"shrink-0 text-doom-faint\">· {call.ranges}</span>\n </span>\n </MessageItemHeader>\n {isError ? (\n <MessageItemBody data-testid=\"tool-result-edit\" className=\"flex flex-col\">\n <MessageItemStatus tone=\"error\">failed</MessageItemStatus>\n {resultTextLines(result, output).map((line, index) => (\n <span key={`${String(index)}-${line}`} className=\"whitespace-pre-wrap break-words text-doom-red\">\n {line}\n </span>\n ))}\n </MessageItemBody>\n ) : view === undefined ? (\n running ? (\n <MessageItemBody data-testid=\"tool-result-edit\">\n <MessageItemStatus tone=\"running\">running</MessageItemStatus>\n </MessageItemBody>\n ) : null\n ) : (\n (() => {\n const { shown, hidden } = collapseLines(view.rows, COLLAPSED_ROWS, expanded);\n return (\n <MessageItemBody data-testid=\"tool-result-edit\" className=\"flex flex-col font-mono\">\n <DiffRows rows={shown} gutter={view.gutter} path={call.path} />\n {hidden > 0 ? (\n <MessageItemStatus expands className=\"pt-1\">\n {hidden} more rows\n </MessageItemStatus>\n ) : null}\n </MessageItemBody>\n );\n })()\n )}\n </>\n )}\n </MessageItem>\n );\n}\n","import { defineToolRenderer } from '@agimon-ai/po-core/web';\n\nimport { EditToolMessage } from './_components/EditToolMessage';\n\nexport default defineToolRenderer({ message: EditToolMessage });\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/po-core/web';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(frontend)/tool/edit.web';\n\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const webPlugin = defineWebPlugin({\n id: 'edit',\n session: {\n get toolRenderers(): WebPluginContributions['toolRenderers'] { return [via({ tools: ['edit'] }, toolEdit)]; },\n },\n});\n"],"mappings":";;;;;AAGA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;AAuBvB,SAAgB,aAAa,MAAuD;CAClF,MAAM,QAAQ,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,MAAM,SAAS;CAC9D,OAAO;EACL,MAAM,OAAO,KAAK,SAAS,WA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zE,MAAa,YAAY,gBAAgB;CACvC,IAAI;CACJ,SAAS,EACP,IAAI,gBAAyD;EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,EAAE,GAAGA,gBAAQ,CAAC;CAAG,EAC9G;AACF,CAAC"}
1
+ {"version":3,"file":"web.mjs","names":["toolEdit"],"sources":["../../src/extensions/workspaces/sessions/(frontend)/tool/_lib/editToolView.ts","../../src/extensions/workspaces/sessions/(frontend)/tool/_components/EditToolMessage.tsx","../../src/extensions/workspaces/sessions/(frontend)/tool/edit.web.tsx","../../generated/web.ts"],"sourcesContent":["import type { ToolResultView } from '@agimon-ai/po-core/web';\n\n/** Pi emits `+12 text`, `-12 text`, ` 12 text`, and a blank-numbered ` ... ` elision between hunks. */\nconst DIFF_ROW_PATTERN = /^([+\\- ])( *\\d*) (.*)$/u;\nconst CONTEXT_MARKER = ' ';\n\nexport type DiffMarker = '+' | '-' | typeof CONTEXT_MARKER;\n\nexport interface DiffRow {\n readonly marker: DiffMarker;\n readonly lineNumber: string;\n readonly content: string;\n}\n\nexport interface EditCallView {\n readonly path: string;\n /** `N range` or `N ranges`, the count the TUI's call heading shows. */\n readonly ranges: string;\n}\n\nexport interface EditResultView {\n readonly rows: readonly DiffRow[];\n /** Widest line number among the rows, in characters, sizing the gutter. */\n readonly gutter: number;\n}\n\n/** What the edit call heading shows: the path and how many ranges the call touches. */\nexport function editCallView(args: Readonly<Record<string, unknown>>): EditCallView {\n const count = Array.isArray(args.edits) ? args.edits.length : 0;\n return {\n path: typeof args.path === 'string' ? args.path : '',\n ranges: `${count} ${count === 1 ? 'range' : 'ranges'}`,\n };\n}\n\nfunction toDiffMarker(value: string | undefined): DiffMarker {\n return value === '+' || value === '-' ? value : CONTEXT_MARKER;\n}\n\n/** Pi's display diff as rows; a line that is not a diff row reads as unnumbered context. */\nexport function parseDiffRows(diff: string): DiffRow[] {\n return diff.split('\\n').map((line) => {\n const expanded = line.replaceAll('\\t', ' ');\n const match = DIFF_ROW_PATTERN.exec(expanded);\n if (!match) return { marker: CONTEXT_MARKER, lineNumber: '', content: expanded };\n return { marker: toDiffMarker(match[1]), lineNumber: (match[2] ?? '').trim(), content: match[3] ?? '' };\n });\n}\n\n/** The diff a successful edit carries in its details; undefined when the details never arrived. */\nexport function editResultView(result: ToolResultView | null): EditResultView | undefined {\n const details = result?.details;\n if (typeof details !== 'object' || details === null) return undefined;\n const diff = (details as { diff?: unknown }).diff;\n if (typeof diff !== 'string' || diff.length === 0) return undefined;\n const rows = parseDiffRows(diff);\n return { rows, gutter: rows.reduce((widest, row) => Math.max(widest, row.lineNumber.length), 1) };\n}\n\n/** The result's text lines, for the error case where the diff never happened. */\nexport function resultTextLines(result: ToolResultView | null, output: string): string[] {\n const text =\n result === null\n ? output\n : result.content\n .flatMap((block) => {\n const record =\n typeof block === 'object' && block !== null ? (block as { type?: unknown; text?: unknown }) : {};\n return record.type === 'text' && typeof record.text === 'string' ? [record.text] : [];\n })\n .join('\\n');\n const lines = text.replaceAll('\\t', ' ').replaceAll('\\r\\n', '\\n').split('\\n');\n while (lines.at(-1) === '') lines.pop();\n return lines;\n}\n","import type { ToolMessageRenderProps } from '@agimon-ai/po-core/web';\nimport {\n MessageItem,\n MessageItemBody,\n MessageItemHeader,\n MessageItemStatus,\n SyntaxLine,\n ToolPathLink,\n toolTone,\n useSyntaxLines,\n} from '@agimon-ai/po-web-components';\n\nimport { type DiffRow, editCallView, editResultView, resultTextLines } from '../_lib/editToolView';\n\n// Po carries a diff on the background the way Magit does: a green wash on\n// added rows, a red wash on removed ones, and the foreground left to the text.\nconst ROW_TONE: Readonly<Record<DiffRow['marker'], string>> = {\n '+': 'bg-po-tint-green text-po-green',\n '-': 'bg-po-tint-red text-po-red',\n ' ': 'text-po-dim',\n};\n\n/**\n * The banded rows, and the grammar over them.\n *\n * Its own component because the colours come from a hook, and the body that\n * renders these rows is chosen inside a render prop. The rows are parsed as\n * one document: a diff is not a file, so a replaced line is seen twice and a\n * split string can colour oddly, which costs a token here and there and never\n * costs the reader the text. The `+` and `-` wash stays underneath, so what\n * changed is still legible when the grammar has coloured the foreground.\n */\nfunction DiffRows({ rows, gutter, path }: { rows: readonly DiffRow[]; gutter: number; path: string }) {\n const spans = useSyntaxLines(rows.map((row) => row.content).join('\\n'), { path });\n return (\n <>\n {rows.map((row, index) => (\n <span key={`${String(index)}-${row.lineNumber}`} className={`flex gap-2 ${ROW_TONE[row.marker]}`}>\n <span className=\"shrink-0 text-right text-po-faint\" style={{ width: `${String(gutter)}ch` }}>\n {row.lineNumber}\n </span>\n <span className=\"w-2 shrink-0\">{row.marker === ' ' ? '' : row.marker}</span>\n <SyntaxLine spans={spans?.[index]} text={row.content} className=\"min-w-0 whitespace-pre-wrap break-words\" />\n </span>\n ))}\n </>\n );\n}\n\n/**\n * The edit tool's timeline item: `path · N ranges` in the header; the display\n * diff from the result's details, banded by row, in the body. A successful\n * edit whose details never arrived shows nothing, and a failed one shows the\n * tool's message in red.\n */\nexport function EditToolMessage({\n args,\n result,\n output,\n running,\n isError,\n fileTabFor,\n openTransientTab,\n}: ToolMessageRenderProps) {\n const call = editCallView(args);\n const view = result === null || isError ? undefined : editResultView(result);\n // The file this edit lands in, opened from the header rather than found\n // again in a file list; plain text when nothing installed can show it.\n const tab = fileTabFor(call.path);\n return (\n <MessageItem tone={toolTone({ running, isError })} expandable>\n {({ expanded }) => (\n <>\n <MessageItemHeader title=\"edit\">\n <span data-testid=\"tool-call-edit\" className=\"flex min-w-0 flex-1 items-center gap-2\">\n <ToolPathLink path={call.path} {...(tab === undefined ? {} : { onOpen: () => openTransientTab(tab) })} />\n <span className=\"shrink-0 text-po-faint\">· {call.ranges}</span>\n </span>\n </MessageItemHeader>\n {!expanded ? null : isError ? (\n <MessageItemBody data-testid=\"tool-result-edit\" className=\"flex flex-col\">\n <MessageItemStatus tone=\"error\">failed</MessageItemStatus>\n {resultTextLines(result, output).map((line, index) => (\n <span key={`${String(index)}-${line}`} className=\"whitespace-pre-wrap break-words text-po-red\">\n {line}\n </span>\n ))}\n </MessageItemBody>\n ) : view === undefined ? (\n running ? (\n <MessageItemBody data-testid=\"tool-result-edit\">\n <MessageItemStatus tone=\"running\">running</MessageItemStatus>\n </MessageItemBody>\n ) : null\n ) : (\n <MessageItemBody data-testid=\"tool-result-edit\" className=\"flex flex-col font-mono\">\n <DiffRows rows={view.rows} gutter={view.gutter} path={call.path} />\n </MessageItemBody>\n )}\n </>\n )}\n </MessageItem>\n );\n}\n","import { defineToolRenderer } from '@agimon-ai/po-core/web';\n\nimport { EditToolMessage } from './_components/EditToolMessage';\n\nexport default defineToolRenderer({ message: EditToolMessage });\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/po-core/web';\n\nimport toolEdit from '../src/extensions/workspaces/sessions/(frontend)/tool/edit.web';\n\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const webPlugin = defineWebPlugin({\n id: 'edit',\n session: {\n get toolRenderers(): WebPluginContributions['toolRenderers'] { return [via({ tools: ['edit'] }, toolEdit)]; },\n },\n});\n"],"mappings":";;;;;AAGA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;AAuBvB,SAAgB,aAAa,MAAuD;CAClF,MAAM,QAAQ,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,MAAM,SAAS;CAC9D,OAAO;EACL,MAAM,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;EAClD,QAAQ,GAAG,MAAM,GAAG,UAAU,IAAI,UAAU;CAC9C;AACF;AAEA,SAAS,aAAa,OAAuC;CAC3D,OAAO,UAAU,OAAO,UAAU,MAAM,QAAQ;AAClD;;AAGA,SAAgB,cAAc,MAAyB;CACrD,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC,KAAK,SAAS;EACpC,MAAM,WAAW,KAAK,WAAW,KAAM,IAAI;EAC3C,MAAM,QAAQ,iBAAiB,KA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IAAmB,MAAK;IAAQ,UAAA;GAAyB,CAAA,GACxD,gBAAgB,QAAQ,MAAM,CAAC,CAAC,KAAK,MAAM,UAC1C,oBAAC,QAAD;IAAuC,WAAU;IAC9C,UAAA;GACG,GAFK,GAAG,OAAO,KAAK,EAAE,GAAG,MAEzB,CACP,CACc;EACf,CAAA,IAAA,SAAS,KAAA,IACX,UACE,oBAAC,iBAAD;GAAiB,eAAY;GAC3B,UAAA,oBAAC,mBAAD;IAAmB,MAAK;IAAU,UAAA;GAA0B,CAAA;EAC7C,CAAA,IACf,OAEJ,oBAAC,iBAAD;GAAiB,eAAY;GAAmB,WAAU;GACxD,UAAA,oBAAC,UAAD;IAAU,MAAM,KAAK;IAAM,QAAQ,KAAK;IAAQ,MAAM,KAAK;GAAO,CAAA;EACnD,CAAA,CAEnB,EAAA,CAAA;CAEO,CAAA;AAEjB;;;ACnGA,IAAA,mBAAe,mBAAmB,EAAE,SAAS,gBAAgB,CAAC;;;ACC9D,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,YAAY,gBAAgB;CACvC,IAAI;CACJ,SAAS,EACP,IAAI,gBAAyD;EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,EAAE,GAAGA,gBAAQ,CAAC;CAAG,EAC9G;AACF,CAAC"}
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { EditToolDetails, ToolDefinition } from "@earendil-works/pi-coding-agent";
2
2
  import { Static, Type } from "typebox";
3
- import { DoomHeadlessTool } from "@agimon-ai/po-core/headless";
3
+ import { PoHeadlessTool } from "@agimon-ai/po-core/headless";
4
4
  //#region src/schemas/editTool.d.ts
5
5
  export declare const HashlineRangeSchema: Type.TObject<{
6
6
  from: Type.TString;
@@ -21,7 +21,7 @@ type EditParams = Static<typeof EditParamsSchema>;
21
21
  //#endregion
22
22
  //#region src/services/editTool/index.d.ts
23
23
  export declare function createHashlineEditTool(): ToolDefinition<typeof EditParamsSchema>;
24
- export declare function createHeadlessEditTool(): DoomHeadlessTool<typeof EditParamsSchema>;
24
+ export declare function createHeadlessEditTool(): PoHeadlessTool<typeof EditParamsSchema>;
25
25
  export declare function executeHashlineEdit(params: EditParams, cwd: string, signal: AbortSignal | undefined): Promise<{
26
26
  content: [{
27
27
  type: 'text';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/schemas/editTool.ts","../src/services/editTool/index.ts"],"mappings":";;;;qBAEa,qBAAmB,KAAA;;;;;qBAWnB,kBAAgB,KAAA;;;;;;;;;KASjB,gBAAgB,cAAc;KAC9B,aAAa,cAAc;;;wBCGvB,0BAA0B,sBAAsB;wBAqBhD,0BAA0B,wBAAwB;wBA2B5C,oBACpB,QAAQ,YACR,aACA,QAAQ,0BACP;EAAU;IAAY;IAAc;;EAAiB,SAAS"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/schemas/editTool.ts","../src/services/editTool/index.ts"],"mappings":";;;;qBAEa,qBAAmB,KAAA;;;;;qBAWnB,kBAAgB,KAAA;;;;;;;;;KASjB,gBAAgB,cAAc;KAC9B,aAAa,cAAc;;;wBCDvB,0BAA0B,sBAAsB;wBAqBhD,0BAA0B,sBAAsB;wBA2B1C,oBACpB,QAAQ,YACR,aACA,QAAQ,0BACP;EAAU;IAAY;IAAc;;EAAiB,SAAS"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-edit",
3
- "version": "0.0.0-alpha.3",
3
+ "version": "0.0.0-alpha.31",
4
4
  "description": "Snapshot-bound hashline edit tool for Pi and Po.",
5
5
  "keywords": [
6
6
  "ai",
@@ -16,7 +16,7 @@
16
16
  "bugs": {
17
17
  "url": "https://github.com/AgiFlow/po/issues"
18
18
  },
19
- "license": "MIT",
19
+ "license": "BUSL-1.1",
20
20
  "author": "Vuong Ngo",
21
21
  "repository": {
22
22
  "type": "git",
@@ -42,6 +42,9 @@
42
42
  "import": "./dist/apiContracts.mjs",
43
43
  "require": "./dist/apiContracts.cjs"
44
44
  },
45
+ "./extensions/native": {
46
+ "import": "./dist/extensions/native.mjs"
47
+ },
45
48
  "./extensions/server": {
46
49
  "types": "./dist/extensions/server.d.mts",
47
50
  "import": "./dist/extensions/server.mjs",
@@ -56,33 +59,48 @@
56
59
  "access": "public"
57
60
  },
58
61
  "dependencies": {
59
- "@agimon-ai/po-core": "0.0.0-alpha.3",
60
- "@agimon-ai/po-hashline": "0.0.0-alpha.3",
61
- "@agimon-ai/po-ui": "0.0.0-alpha.3",
62
- "@agimon-ai/po-web-components": "0.0.0-alpha.3",
63
- "@deepseek-ai/cordis": "4.0.4",
64
- "typebox": "1.3.36"
62
+ "@agimon-ai/po-core": "0.0.0-alpha.31",
63
+ "@agimon-ai/po-hashline": "0.0.0-alpha.31",
64
+ "@agimon-ai/po-ui": "0.0.0-alpha.31",
65
+ "@agimon-ai/po-web-components": "0.0.0-alpha.31",
66
+ "@deepseek-ai/cordis": "4.0.5",
67
+ "typebox": "1.3.37"
65
68
  },
66
69
  "devDependencies": {
67
- "@agimon-ai/po-build": "0.0.0-alpha.3",
68
- "@earendil-works/pi-coding-agent": "1.2.0",
70
+ "@agimon-ai/po-build": "0.0.0-alpha.31",
71
+ "@agimon-ai/po-native-components": "0.0.0-alpha.31",
72
+ "@earendil-works/pi-coding-agent": "1.3.0",
69
73
  "@tanstack/react-store": "0.11.2",
70
74
  "@tanstack/store": "0.11.2",
71
- "@types/node": "25.9.9",
75
+ "@types/node": "26.6.5",
72
76
  "@types/react": "19.3.0",
73
- "@vitest/coverage-v8": "5.0.3",
77
+ "@vitest/coverage-v8": "5.0.4",
74
78
  "react": "19.3.0",
75
79
  "react-dom": "19.3.0",
80
+ "react-native": "0.86.3",
81
+ "react-native-unistyles": "3.5.3",
76
82
  "tsdown": "0.23.1",
77
83
  "typescript": "7.0.2",
78
- "vitest": "5.0.3"
84
+ "vitest": "5.0.4"
79
85
  },
80
86
  "peerDependencies": {
81
- "@earendil-works/pi-coding-agent": "1.2.0"
87
+ "@agimon-ai/po-native-components": "0.0.0-alpha.31",
88
+ "@earendil-works/pi-coding-agent": "1.3.0",
89
+ "react-native": "0.86.3",
90
+ "react-native-unistyles": "^3.5.3"
82
91
  },
83
92
  "peerDependenciesMeta": {
84
93
  "@earendil-works/pi-coding-agent": {
85
94
  "optional": true
95
+ },
96
+ "@agimon-ai/po-native-components": {
97
+ "optional": true
98
+ },
99
+ "react-native": {
100
+ "optional": true
101
+ },
102
+ "react-native-unistyles": {
103
+ "optional": true
86
104
  }
87
105
  },
88
106
  "engines": {
@@ -102,6 +120,14 @@
102
120
  ]
103
121
  }
104
122
  },
123
+ "poNative": {
124
+ "pluginId": "edit",
125
+ "channels": [],
126
+ "client": "./dist/extensions/native.mjs",
127
+ "scopes": [
128
+ "session"
129
+ ]
130
+ },
105
131
  "poServer": {
106
132
  "entry": "./generated/server.ts",
107
133
  "dist": "./dist/extensions/server.mjs",
@@ -125,7 +151,7 @@
125
151
  "build": "tsdown && tsdown --config tsdown.mcp.config.ts",
126
152
  "build:mcp": "tsdown --config tsdown.mcp.config.ts",
127
153
  "test": "vitest --run",
128
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.web.json && tsc --noEmit -p tsconfig.mcp.json",
154
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.web.json && tsc --noEmit -p tsconfig.native.json && tsc --noEmit -p tsconfig.mcp.json",
129
155
  "lint": "oxlint . && oxfmt . --check",
130
156
  "fixcode": "oxlint . --fix && oxfmt ."
131
157
  }