-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.ts
More file actions
1459 lines (1235 loc) · 49.7 KB
/
index.ts
File metadata and controls
1459 lines (1235 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* OpenCode Morph Plugin v2
*
* Integrates Morph SDK for fast apply, WarpGrep codebase search, and shell env.
* Uses MorphClient for shared config (API key, timeout, retries) across all tools.
*
* @see https://docs.morphllm.com/quickstart
*/
import { type Plugin, tool } from "@opencode-ai/plugin";
import { MorphClient, WarpGrepClient, CompactClient } from "@morphllm/morphsdk";
import type { WarpGrepResult, CompactResult } from "@morphllm/morphsdk";
import type { Part, TextPart, ToolPart, Message } from "@opencode-ai/sdk";
import { isAbsolute, resolve as resolvePath } from "node:path";
// Config from environment — only MORPH_API_KEY is required
const MORPH_API_KEY = process.env.MORPH_API_KEY;
const MORPH_API_URL = "https://api.morphllm.com";
const MORPH_TIMEOUT = 30000;
const MORPH_WARP_GREP_TIMEOUT = 60000;
const MORPH_COMPACT_TIMEOUT = 60000;
const GITHUB_RESOLVER_TIMEOUT = 10000;
const GITHUB_REPO_API_URL = "https://api.github.com/repos";
const GITHUB_REPO_SEARCH_URL = "https://api.github.com/search/repositories";
const GITHUB_REPO_SUGGESTION_LIMIT = 5;
// Compaction config — threshold and ratio are user-tunable
// Approximate: ~3 characters per token (rough estimate for threshold math)
const CHARS_PER_TOKEN = 3;
// Compact when effective context reaches this fraction of model's max context window
const COMPACT_CONTEXT_THRESHOLD = parseFloat(
process.env.MORPH_COMPACT_CONTEXT_THRESHOLD || "0.7",
);
// Number of recent messages to keep uncompacted (full fidelity for the LLM).
// Default 1 = keep only the latest user prompt; compact all prior messages.
const COMPACT_PRESERVE_RECENT = parseInt(
process.env.MORPH_COMPACT_PRESERVE_RECENT || "1",
10,
);
const COMPACT_RATIO = parseFloat(
process.env.MORPH_COMPACT_RATIO || "0.3",
);
// Optional fixed token limit — overrides the percentage-based threshold.
// e.g. MORPH_COMPACT_TOKEN_LIMIT=20000 → compact at 20k tokens regardless of model window
const COMPACT_TOKEN_LIMIT = process.env.MORPH_COMPACT_TOKEN_LIMIT
? parseInt(process.env.MORPH_COMPACT_TOKEN_LIMIT, 10)
: null;
/**
* Feature flags — users can disable specific capabilities.
* All default to true (enabled). Set to "false" to disable.
*/
const MORPH_EDIT_ENABLED = process.env.MORPH_EDIT !== "false";
const MORPH_WARPGREP_ENABLED = process.env.MORPH_WARPGREP !== "false";
const MORPH_WARPGREP_GITHUB_ENABLED =
process.env.MORPH_WARPGREP_GITHUB !== "false";
const MORPH_COMPACT_ENABLED = process.env.MORPH_COMPACT !== "false";
/**
* Agents that are blocked from using morph_edit by default.
* Users can override by setting MORPH_ALLOW_READONLY_AGENTS=true
*/
const READONLY_AGENTS = ["plan", "explore"];
const ALLOW_READONLY_AGENTS =
process.env.MORPH_ALLOW_READONLY_AGENTS === "true";
/** Plugin version */
const PLUGIN_VERSION = "2.0.0";
/** Canonical marker string used for lazy edit placeholders */
const EXISTING_CODE_MARKER = "// ... existing code ...";
const MORPH_ROUTING_HINT_HEADER = "Morph plugin routing hints:";
/**
* Shared MorphClient — FastApply uses morph.fastApply.applyEdit()
* with MORPH_API_URL passed as per-call override.
*/
const morph = MORPH_API_KEY
? new MorphClient({
apiKey: MORPH_API_KEY,
timeout: MORPH_TIMEOUT,
})
: null;
/**
* Separate WarpGrep client with its own timeout (typically longer than fast apply).
*/
const warpGrep = MORPH_API_KEY
? new WarpGrepClient({
morphApiKey: MORPH_API_KEY,
morphApiUrl: MORPH_API_URL,
timeout: MORPH_WARP_GREP_TIMEOUT,
})
: null;
/**
* Separate CompactClient for context compaction.
*/
const compactClient = MORPH_API_KEY
? new CompactClient({
morphApiKey: MORPH_API_KEY,
morphApiUrl: MORPH_API_URL,
timeout: MORPH_COMPACT_TIMEOUT,
})
: null;
/**
* Model context window size in tokens. Updated from chat.params hook.
* Default is conservative — actual value captured on first LLM call.
*/
let modelContextTokens = 200_000;
/**
* Frozen compaction state. Once messages are compacted, the result is
* frozen and reused identically on every subsequent messages.transform call.
* This preserves prompt cache stability (the prefix bytes never change).
*
* On re-compaction, the old frozen block is discarded entirely and a new
* one is built from only the uncompacted messages (never double-compact).
*/
let compactionState: {
frozenMessages: { info: Message; parts: Part[] }[];
compactedUpToIndex: number;
frozenChars: number;
} | null = null;
/**
* Normalize code_edit input from LLM tool calls.
*
* Agents frequently wrap tool arguments in markdown fences (```lang ... ```).
* When this is nested inside Morph's <update> XML tag, it confuses the merge
* model. This function strips a single outer fence pair using line-based parsing.
*/
function normalizeCodeEditInput(codeEdit: string): string {
const trimmed = codeEdit.trim();
const lines = trimmed.split("\n");
if (lines.length < 3) return codeEdit;
const firstLine = lines[0];
const lastLine = lines[lines.length - 1];
if (/^```[\w-]*$/.test(firstLine) && /^```$/.test(lastLine)) {
return lines.slice(1, -1).join("\n");
}
return codeEdit;
}
/**
* Serialize a Part into a text representation for compaction input.
* Tool outputs, text, and reasoning are included. Other part types are
* represented as brief markers to preserve structure without bulk.
*/
function serializePart(part: Part): string {
switch (part.type) {
case "text":
return (part as TextPart).text;
case "tool": {
const tp = part as ToolPart;
const state = tp.state;
if (state.status === "completed") {
const inputStr = JSON.stringify(state.input).slice(0, 500);
const outputStr = (state.output || "").slice(0, 2000);
return `[Tool: ${tp.tool}] ${inputStr}\nOutput: ${outputStr}`;
}
if (state.status === "error") {
return `[Tool: ${tp.tool}] Error: ${state.error}`;
}
return `[Tool: ${tp.tool}] ${state.status}`;
}
case "reasoning":
return `[Reasoning] ${(part as { text: string }).text}`;
default:
return `[${part.type}]`;
}
}
/**
* Convert OpenCode messages to the format Morph compact expects.
*/
function messagesToCompactInput(
messages: { info: Message; parts: Part[] }[],
): { role: string; content: string }[] {
return messages
.map((m) => ({
role: m.info.role,
content: m.parts.map(serializePart).join("\n"),
}))
.filter((m) => m.content.length > 0);
}
/**
* Estimate total character count across all message parts.
*/
function estimateTotalChars(
messages: { info: Message; parts: Part[] }[],
): number {
let total = 0;
for (const m of messages) {
for (const part of m.parts) {
if (part.type === "text") total += (part as TextPart).text.length;
else if (part.type === "tool") {
const tp = part as ToolPart;
if (tp.state.status === "completed") {
total += (tp.state.output || "").length;
total += JSON.stringify(tp.state.input).length;
}
}
}
}
return total;
}
function resolveSessionFilepath(
targetFilepath: string,
sessionDirectory: string,
): string {
return isAbsolute(targetFilepath)
? targetFilepath
: resolvePath(sessionDirectory, targetFilepath);
}
function resolveSessionRepoRoot(
sessionDirectory: string,
sessionWorktree: string,
): string {
return sessionWorktree || sessionDirectory;
}
function appendRuntimeNotes(description: string, notes: string[]): string {
if (notes.length === 0) return description;
return `${description}\n\nRuntime notes:\n${notes.map((note) => `- ${note}`).join("\n")}`;
}
function buildToolRuntimeNotes(toolID: string): string[] {
switch (toolID) {
case "morph_edit": {
const notes = [
"Relative paths resolve from the active session directory.",
];
if (!ALLOW_READONLY_AGENTS) {
notes.push(
`Blocked in readonly agents: ${READONLY_AGENTS.join(", ")}.`,
);
}
if (!MORPH_API_KEY) {
notes.push("Currently unavailable until MORPH_API_KEY is configured.");
}
return notes;
}
case "warpgrep_codebase_search": {
const notes = [
"Searches the current project worktree, not just the immediate cwd.",
];
if (!MORPH_API_KEY) {
notes.push("Currently unavailable until MORPH_API_KEY is configured.");
}
return notes;
}
case "warpgrep_github_search": {
const notes = [
"Use this for public GitHub source questions, not the current checked-out repo.",
];
if (!MORPH_API_KEY) {
notes.push("Currently unavailable until MORPH_API_KEY is configured.");
}
return notes;
}
default:
return [];
}
}
function buildMorphSystemRoutingHint(): string | null {
if (!MORPH_API_KEY) {
return [
MORPH_ROUTING_HINT_HEADER,
"- Morph remote tools are currently unavailable because MORPH_API_KEY is not configured.",
"- Use native edit/write/grep tools until Morph credentials are configured.",
].join("\n");
}
const lines = [MORPH_ROUTING_HINT_HEADER];
if (MORPH_EDIT_ENABLED) {
lines.push(
"- Prefer morph_edit for large or scattered edits inside existing files.",
);
lines.push("- Use native edit for small exact replacements.");
lines.push("- Use write for brand new files.");
if (!ALLOW_READONLY_AGENTS) {
lines.push(
`- morph_edit is blocked in readonly agents: ${READONLY_AGENTS.join(", ")}.`,
);
}
}
if (MORPH_WARPGREP_ENABLED) {
lines.push(
"- Use warpgrep_codebase_search for exploratory local codebase questions.",
);
}
if (MORPH_WARPGREP_GITHUB_ENABLED) {
lines.push(
"- Use warpgrep_github_search for public GitHub source questions.",
);
}
return lines.length > 1 ? lines.join("\n") : null;
}
/**
* Minimal check for a plausible file path on any OS:
* - at least one path separator (/ or \) OR a dot-extension
* - not empty / whitespace-only
*/
const PLAUSIBLE_PATH_RE = /[/\\]|\.[\w]+$/;
function isValidContext(ctx: { file: string; content: string }): boolean {
return Boolean(ctx.file) && PLAUSIBLE_PATH_RE.test(ctx.file) && ctx.content.length > 0;
}
/**
* Format WarpGrep results for tool output
*/
function formatWarpGrepResult(result: WarpGrepResult): string {
if (!result.success) {
return `Search failed: ${result.error || "search returned no error details."}`;
}
if (!result.contexts || result.contexts.length === 0) {
return "No relevant code found. Try rephrasing your search term.";
}
const valid = result.contexts.filter(isValidContext);
if (valid.length === 0) {
const sample = result.contexts.slice(0, 3).map((c) => c.file);
return `Search returned malformed file contexts (file values: ${JSON.stringify(sample)}).
Fallback: use \`grep\` + \`read\` for local code search.`;
}
const parts: string[] = [];
parts.push("Relevant context found:");
for (const ctx of valid) {
const rangeStr =
!ctx.lines || ctx.lines === "*"
? "*"
: ctx.lines.map(([s, e]) => `${s}-${e}`).join(",");
parts.push(`- ${ctx.file}:${rangeStr}`);
}
parts.push("\nFile contents:\n");
for (const ctx of valid) {
const rangeStr =
!ctx.lines || ctx.lines === "*"
? ""
: ` lines="${ctx.lines.map(([s, e]) => `${s}-${e}`).join(",")}"`;
parts.push(`<file path="${ctx.file}"${rangeStr}>`);
parts.push(ctx.content);
parts.push("</file>\n");
}
return parts.join("\n");
}
type PublicRepoContextSearchArgs = {
search_term: string;
owner_repo?: string;
github_url?: string;
branch?: string;
};
type GitHubRepo = string; // "owner/repo"
type GitHubRepoSuggestion = {
fullName: string;
htmlUrl: string;
description?: string;
stars: number;
ownerLogin: string;
name: string;
};
type GitHubRepoLookupResult =
| {
status: "found";
fullName: string;
defaultBranch?: string;
htmlUrl?: string;
}
| {
status: "not_found";
detail: string;
}
| {
status: "unavailable";
detail: string;
};
const GITHUB_OWNER_REPO_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
function tokenizeSuggestionQuery(text: string): string[] {
return text
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter((token) => token.length >= 2);
}
function buildGitHubSuggestionQueries(
repo: GitHubRepo,
searchTerm: string,
): string[] {
const [owner, repoName] = repo.split("/");
const searchTokens = tokenizeSuggestionQuery(searchTerm).slice(0, 3);
const queries = new Set<string>();
if (owner) queries.add(`user:${owner}`);
if (owner && repoName) queries.add(`${repoName} user:${owner}`);
if (repoName) queries.add(repoName);
if (searchTokens.length > 0 && repoName) {
queries.add(`${repoName} ${searchTokens.join(" ")}`);
}
return Array.from(queries).slice(0, 4);
}
function formatPublicRepoResolutionFailure(
repo: GitHubRepo,
detail?: string,
suggestions: GitHubRepoSuggestion[] = [],
): string {
const parts: string[] = [
`Repository not found: ${repo}\n\nThis repository does not exist or is private. Do NOT keep guessing other repo names.`,
];
if (suggestions.length > 0) {
const list = suggestions.map((s) => `- ${s.fullName}${s.description ? ` - ${s.description}` : ""}`).join("\n");
parts.push(`Public repos found under this org:\n${list}\n\nIf one of these looks right, retry with that owner_repo.`);
}
parts.push(`If the package or SDK is closed-source or private:\n- Check the ecosystem registry or package page for repository metadata before guessing more names\n- Use the registry that matches the environment: npm for Node/TypeScript, crates.io for Rust, PyPI for Python, pkg.go.dev for Go, etc.\n- The real source repo may be under a different org or name\n- Stop trying variations and report that the source is not publicly available`);
return parts.join("\n\n");
}
function resolvePublicRepoLocator(
args: PublicRepoContextSearchArgs,
): { repo: GitHubRepo } | { error: string } {
const ownerRepo = args.owner_repo?.trim();
const githubUrl = args.github_url?.trim();
if (ownerRepo && githubUrl) {
return {
error: `Error: Provide either owner_repo or github_url, not both.
Use owner_repo for values like "owner/repo" or github_url for full URLs like "https://github.com/owner/repo".`,
};
}
if (!ownerRepo && !githubUrl) {
return {
error: `Error: Missing repository target.
Provide exactly one of:
- owner_repo: "owner/repo"
- github_url: "https://github.com/owner/repo"`,
};
}
if (ownerRepo) {
if (!GITHUB_OWNER_REPO_PATTERN.test(ownerRepo)) {
return {
error: `Error: owner_repo must be a GitHub repository in "owner/repo" format.
Received: "${ownerRepo}"
Examples:
- "owner/repo"
- "org/project"
- "team/package"
If you have a full URL, use github_url instead.`,
};
}
return { repo: ownerRepo };
}
let parsed: URL;
try {
parsed = new URL(githubUrl!);
} catch {
return {
error: `Error: github_url must be a valid GitHub repository URL.
Received: "${githubUrl}"
Example:
- "https://github.com/owner/repo"`,
};
}
if (!["github.com", "www.github.com"].includes(parsed.hostname)) {
return {
error: `Error: github_url must point to github.com.
Received host: "${parsed.hostname}"
Example:
- "https://github.com/owner/repo"`,
};
}
const pathParts = parsed.pathname
.split("/")
.map((part) => part.trim())
.filter(Boolean);
if (pathParts.length < 2) {
return {
error: `Error: github_url must include both owner and repository name.
Received: "${githubUrl}"
Example:
- "https://github.com/owner/repo"`,
};
}
const owner = pathParts[0]!;
const repoName = pathParts[1]!.replace(/\.git$/, "");
const canonicalRepo = `${owner}/${repoName}`;
if (!GITHUB_OWNER_REPO_PATTERN.test(canonicalRepo)) {
return {
error: `Error: github_url did not resolve to a valid GitHub owner/repo locator.
Received: "${githubUrl}"`,
};
}
return { repo: canonicalRepo };
}
function githubHeaders(): Record<string, string> {
return {
Accept: "application/vnd.github+json",
"User-Agent": "@morphllm/opencode-morph-plugin",
};
}
async function withGitHubTimeout<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), GITHUB_RESOLVER_TIMEOUT);
try {
return await fn(ctrl.signal);
} finally {
clearTimeout(timer);
}
}
async function lookupGitHubRepository(
repo: GitHubRepo,
): Promise<GitHubRepoLookupResult> {
return withGitHubTimeout(async (signal) => {
try {
const response = await fetch(`${GITHUB_REPO_API_URL}/${repo}`, {
headers: githubHeaders(),
signal,
});
if (response.status === 404) return { status: "not_found", detail: "GitHub repository not found" };
if (!response.ok) return { status: "unavailable", detail: `GitHub repo lookup failed with status ${response.status}` };
const body = (await response.json()) as {
full_name?: string;
default_branch?: string;
html_url?: string;
};
return {
status: "found",
fullName: body.full_name || repo,
defaultBranch: body.default_branch,
htmlUrl: body.html_url,
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown GitHub repo lookup error";
return { status: "unavailable", detail: message };
}
});
}
async function fetchGitHubRepoSuggestions(
repo: GitHubRepo,
searchTerm: string,
): Promise<GitHubRepoSuggestion[]> {
return withGitHubTimeout(async (signal) => {
const queries = buildGitHubSuggestionQueries(repo, searchTerm);
const results = await Promise.all(
queries.map(async (query) => {
const url = new URL(GITHUB_REPO_SEARCH_URL);
url.searchParams.set("q", query);
url.searchParams.set("sort", "stars");
url.searchParams.set("order", "desc");
url.searchParams.set("per_page", String(GITHUB_REPO_SUGGESTION_LIMIT));
const response = await fetch(url.toString(), { headers: githubHeaders(), signal });
if (!response.ok) return [];
const body = (await response.json()) as {
items?: Array<{
full_name?: string;
html_url?: string;
description?: string | null;
stargazers_count?: number;
name?: string;
owner?: { login?: string };
}>;
};
return (body.items || []).filter(
(item) => item.full_name && item.html_url && item.name && item.owner?.login,
);
}),
);
const candidates = new Map<string, GitHubRepoSuggestion>();
for (const items of results) {
for (const item of items) {
if (!candidates.has(item.full_name!)) {
candidates.set(item.full_name!, {
fullName: item.full_name!,
htmlUrl: item.html_url!,
description: item.description || undefined,
stars: item.stargazers_count || 0,
ownerLogin: item.owner!.login!,
name: item.name!,
});
}
}
}
return Array.from(candidates.values()).slice(0, GITHUB_REPO_SUGGESTION_LIMIT);
});
}
const MorphPlugin: Plugin = async ({ directory, worktree, client }) => {
const log = async (
level: "debug" | "info" | "warn" | "error",
message: string,
) => {
try {
await client.app.log({
body: {
service: "morph",
level,
message,
},
});
} catch {
process.stderr.write(`[morph] ${message}\n`);
}
};
const showToast = async (
variant: "info" | "success" | "warning" | "error",
message: string,
) => {
try {
await client.tui?.showToast({
body: { title: "Morph Compact", message, variant, duration: 2000 },
});
} catch {}
};
if (!MORPH_API_KEY) {
await log(
"warn",
"MORPH_API_KEY not set - morph tools will be disabled",
);
} else {
const features = [
MORPH_EDIT_ENABLED && "edit",
MORPH_WARPGREP_ENABLED && "warpgrep",
MORPH_WARPGREP_GITHUB_ENABLED && "warpgrep-github",
MORPH_COMPACT_ENABLED && "compact",
].filter(Boolean);
await log("info", `Plugin v${PLUGIN_VERSION} loaded [${features.join(", ")}]`);
}
// Build tool map conditionally based on feature flags
const tools: Record<string, ReturnType<typeof tool>> = {};
if (MORPH_EDIT_ENABLED) {
tools.morph_edit = tool({
description: `Edit existing files using partial code snippets with "// ... existing code ..." markers. Morph's AI merges your changes into the full file.
WHEN TO USE morph_edit vs edit:
- morph_edit: large files (300+ lines), multiple scattered changes, complex refactoring, whitespace-sensitive edits
- native edit: small exact string replacements, simple renames, single-line fixes (faster, no API call)
- native write: creating new files from scratch
FORMAT — use "// ... existing code ..." to represent unchanged sections:
// ... existing code ...
FIRST_EDIT
// ... existing code ...
SECOND_EDIT
// ... existing code ...
CRITICAL RULES:
- ALWAYS wrap changes with markers at start AND end (omitting markers DELETES surrounding code)
- Include 1-2 unique context lines around each edit to anchor the location precisely
- Write a specific 'instructions' param: "I am adding X to function Y" not "update code"
- Preserve exact indentation
- For deletions: show surrounding context, omit the deleted lines
- Batch multiple edits to the same file in one call
DISAMBIGUATION — when a file has repeated patterns, include enough unique context:
BAD: just "return result;" (matches many places)
GOOD: include the unique function signature above it
FALLBACK: If morph_edit fails (API error, timeout), use the native 'edit' tool with exact oldString/newString matching.`,
args: {
target_filepath: tool.schema
.string()
.describe("Path of the file to modify"),
instructions: tool.schema
.string()
.describe(
"Brief first-person description of what you're changing. Used to disambiguate uncertainty in the edit.",
),
code_edit: tool.schema
.string()
.describe(
'The code changes wrapped with "// ... existing code ..." markers for unchanged sections',
),
},
async execute(args, context) {
const { target_filepath, instructions, code_edit } = args;
const normalizedCodeEdit = normalizeCodeEditInput(code_edit);
// Guard 1: Block readonly agents
if (
!ALLOW_READONLY_AGENTS &&
READONLY_AGENTS.includes(context.agent)
) {
await log(
"debug",
`Blocked morph_edit in readonly agent: ${context.agent}`,
);
return `Error: morph_edit is not available in ${context.agent} mode.
The ${context.agent} agent is read-only and cannot modify files.
Options:
1. Switch to 'build' mode (Tab key) to make changes
2. Use the native 'edit' tool if permitted by your agent config
3. Set MORPH_ALLOW_READONLY_AGENTS=true to override this restriction`;
}
const filepath = resolveSessionFilepath(
target_filepath,
directory,
);
if (!MORPH_API_KEY) {
return `Error: MORPH_API_KEY not configured.
To use morph_edit, set the MORPH_API_KEY environment variable.
Get your API key at: https://morphllm.com/dashboard/api-keys
Alternatively, use the native 'edit' tool for this change.`;
}
// Read the original file
let originalCode: string;
try {
const file = Bun.file(filepath);
if (!(await file.exists())) {
if (!normalizedCodeEdit.includes(EXISTING_CODE_MARKER)) {
await Bun.write(filepath, normalizedCodeEdit);
return `Created new file: ${target_filepath}\n\nLines: ${normalizedCodeEdit.split("\n").length}`;
}
return `Error: File not found: ${target_filepath}
The file doesn't exist and the code_edit contains lazy markers.
For new files, provide the complete content without "${EXISTING_CODE_MARKER}" markers.`;
}
originalCode = await file.text();
} catch (err) {
const error = err as Error;
return `Error reading file ${target_filepath}: ${error.message}`;
}
// Guard 2: Pre-flight marker check
const hasMarkers = normalizedCodeEdit.includes(EXISTING_CODE_MARKER);
const originalLineCount = originalCode.split("\n").length;
if (!hasMarkers && originalLineCount > 10) {
return `Error: Missing "${EXISTING_CODE_MARKER}" markers.
Your code_edit would replace the entire file (${originalLineCount} lines) because it contains no markers.
This is almost certainly unintended and would cause code loss.
To fix, wrap your changes with markers:
${EXISTING_CODE_MARKER}
YOUR_CHANGES_HERE
${EXISTING_CODE_MARKER}
If you truly want to replace the entire file, use the 'write' tool instead.`;
}
if (!hasMarkers && originalLineCount > 3) {
await log(
"warn",
`No markers in code_edit for ${target_filepath} (${originalLineCount} lines). Proceeding with full replacement.`,
);
}
// Call Morph SDK to merge the edit
const startTime = Date.now();
const result = await morph!.fastApply.applyEdit(
{
originalCode,
codeEdit: normalizedCodeEdit,
instruction: instructions,
filepath: target_filepath,
},
{
morphApiUrl: MORPH_API_URL,
generateUdiff: true,
},
);
const apiDuration = Date.now() - startTime;
if (!result.success || !result.mergedCode) {
return `Morph API failed: ${result.error}
Suggestion: Try using the native 'edit' tool instead with exact string replacement.
The edit tool requires matching the exact text in the file.`;
}
const mergedCode = result.mergedCode;
// Guard 3: Marker leakage detection
const originalHadMarker = originalCode.includes(EXISTING_CODE_MARKER);
if (
hasMarkers &&
!originalHadMarker &&
mergedCode.includes(EXISTING_CODE_MARKER)
) {
await log(
"warn",
`Marker leakage detected in merged output for ${target_filepath}`,
);
return `Morph API produced unsafe output for ${target_filepath}.
Detected placeholder marker text ("${EXISTING_CODE_MARKER}") in merged output.
This means the merge model treated markers as literal code instead of expanding them.
No file changes were written.
Options:
1. Retry with more concrete surrounding context in code_edit
2. Use the native 'edit' tool for exact string replacement
3. Break the change into smaller, more targeted edits`;
}
// Guard 4: Catastrophic truncation detection
const mergedLineCount = mergedCode.split("\n").length;
const charLoss =
(originalCode.length - mergedCode.length) / originalCode.length;
const lineLoss =
(originalLineCount - mergedLineCount) / originalLineCount;
if (hasMarkers && charLoss > 0.6 && lineLoss > 0.5) {
await log(
"warn",
`Catastrophic truncation detected for ${target_filepath}: ${Math.round(charLoss * 100)}% char loss, ${Math.round(lineLoss * 100)}% line loss`,
);
return `Morph API produced a potentially destructive merge for ${target_filepath}.
Original: ${originalLineCount} lines (${originalCode.length} chars)
Merged: ${mergedLineCount} lines (${mergedCode.length} chars)
Loss: ${Math.round(charLoss * 100)}% characters, ${Math.round(lineLoss * 100)}% lines
Because markers were provided, this large shrink is likely unintended.
No file changes were written.
Options:
1. Retry with more precise anchors in code_edit
2. Use the native 'edit' tool for exact string replacement
3. Break the change into smaller edits`;
}
// Write the merged result
try {
await Bun.write(filepath, mergedCode);
} catch (err) {
const error = err as Error;
return `Error writing file ${target_filepath}: ${error.message}`;
}
// Use SDK-provided diff and change stats
const udiff = result.udiff || "No changes detected";
const { linesAdded, linesRemoved } = result.changes;
const originalLines = originalCode.split("\n").length;
const mergedLines = mergedCode.split("\n").length;
return `Applied edit to ${target_filepath}
+${linesAdded} -${linesRemoved} lines | ${originalLines} -> ${mergedLines} total | ${apiDuration}ms
\`\`\`diff
${udiff.slice(0, 3000)}${udiff.length > 3000 ? "\n... (truncated)" : ""}
\`\`\``;
},
});
}
if (MORPH_WARPGREP_ENABLED) {
tools.warpgrep_codebase_search = tool({
description: `Fast agentic codebase search. Uses ripgrep, file reading, and directory listing across multiple turns to find relevant code contexts.
Use this for exploratory searches like "Find the authentication flow", "How does error handling work", "Where is the database connection configured". Returns relevant file sections with line numbers.
For exact keyword searches (specific function names, variable names), prefer grep/ripgrep directly.`,
args: {
search_term: tool.schema
.string()
.describe(
"Natural language search query describing what to find in the codebase",
),
},
async execute(args, context) {
if (!MORPH_API_KEY) {
return `Error: MORPH_API_KEY not configured.
To use warpgrep_codebase_search, set the MORPH_API_KEY environment variable.
Get your API key at: https://morphllm.com/dashboard/api-keys`;
}
const startTime = Date.now();
try {
const generator = warpGrep!.execute({
searchTerm: args.search_term,
repoRoot: resolveSessionRepoRoot(
directory,
worktree,
),
streamSteps: true,
});
let turnCount = 0;
let result: WarpGrepResult;
for (;;) {
const { value, done } = await generator.next();
if (done) {
result = value;
break;
}
turnCount = value.turn;
await log(
"debug",
`WarpGrep turn ${value.turn}: ${value.toolCalls?.map((tc: { name: string }) => tc.name).join(", ") ?? "..."}`,
);
}
const duration = Date.now() - startTime;
const contextCount = result.contexts?.length ?? 0;
await log(
"info",
`WarpGrep: ${contextCount} contexts in ${turnCount} turns (${duration}ms)`,