opencode-manifold 0.4.13 → 0.4.15

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.
Files changed (3) hide show
  1. package/dist/index.js +1480 -1819
  2. package/dist/tui.js +83 -47
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,710 +1,984 @@
1
1
  import { createRequire } from "node:module";
2
2
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
3
 
4
- // src/tui.ts
4
+ // src/init.ts
5
+ import { readFile, writeFile, mkdir, readdir } from "fs/promises";
5
6
  import { existsSync } from "fs";
6
- import { join } from "path";
7
+ import { join, dirname } from "path";
8
+ import { fileURLToPath } from "url";
7
9
  import { homedir } from "os";
8
- import { readFile, writeFile, readdir } from "fs/promises";
9
-
10
- // node_modules/js-yaml/dist/js-yaml.mjs
11
- /*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
12
- function isNothing(subject) {
13
- return typeof subject === "undefined" || subject === null;
14
- }
15
- function isObject(subject) {
16
- return typeof subject === "object" && subject !== null;
17
- }
18
- function toArray(sequence) {
19
- if (Array.isArray(sequence))
20
- return sequence;
21
- else if (isNothing(sequence))
10
+ import { createRequire as createRequire2 } from "module";
11
+ var __dirname2 = dirname(fileURLToPath(import.meta.url));
12
+ var require2 = createRequire2(import.meta.url);
13
+ var bundledTemplatesDir = join(__dirname2, "..", "src", "templates");
14
+ var globalTemplatesDir = join(homedir(), ".config", "opencode", "manifold");
15
+ async function copyFiles(src, dest) {
16
+ if (!existsSync(src))
22
17
  return [];
23
- return [sequence];
24
- }
25
- function extend(target, source) {
26
- var index, length, key, sourceKeys;
27
- if (source) {
28
- sourceKeys = Object.keys(source);
29
- for (index = 0, length = sourceKeys.length;index < length; index += 1) {
30
- key = sourceKeys[index];
31
- target[key] = source[key];
18
+ await mkdir(dest, { recursive: true });
19
+ const copied = [];
20
+ const entries = await readdir(src, { withFileTypes: true });
21
+ for (const entry of entries) {
22
+ const srcPath = join(src, entry.name);
23
+ const destPath = join(dest, entry.name);
24
+ if (entry.isDirectory()) {
25
+ const subCopied = await copyFiles(srcPath, destPath);
26
+ if (subCopied.length > 0) {
27
+ copied.push(entry.name);
28
+ }
29
+ } else {
30
+ await writeFile(destPath, await readFile(srcPath));
31
+ copied.push(entry.name);
32
32
  }
33
33
  }
34
- return target;
35
- }
36
- function repeat(string, count) {
37
- var result = "", cycle;
38
- for (cycle = 0;cycle < count; cycle += 1) {
39
- result += string;
40
- }
41
- return result;
42
- }
43
- function isNegativeZero(number) {
44
- return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
34
+ return copied;
45
35
  }
46
- var isNothing_1 = isNothing;
47
- var isObject_1 = isObject;
48
- var toArray_1 = toArray;
49
- var repeat_1 = repeat;
50
- var isNegativeZero_1 = isNegativeZero;
51
- var extend_1 = extend;
52
- var common = {
53
- isNothing: isNothing_1,
54
- isObject: isObject_1,
55
- toArray: toArray_1,
56
- repeat: repeat_1,
57
- isNegativeZero: isNegativeZero_1,
58
- extend: extend_1
59
- };
60
- function formatError(exception, compact) {
61
- var where = "", message = exception.reason || "(unknown reason)";
62
- if (!exception.mark)
63
- return message;
64
- if (exception.mark.name) {
65
- where += 'in "' + exception.mark.name + '" ';
36
+ async function ensureGlobalTemplates(ctx) {
37
+ await ctx.client.app.log({
38
+ body: {
39
+ service: "opencode-manifold",
40
+ level: "info",
41
+ message: "Synchronizing global templates..."
42
+ }
43
+ });
44
+ if (!existsSync(bundledTemplatesDir)) {
45
+ await ctx.client.app.log({
46
+ body: {
47
+ service: "opencode-manifold",
48
+ level: "error",
49
+ message: `Bundled templates not found at ${bundledTemplatesDir}`
50
+ }
51
+ });
52
+ return;
66
53
  }
67
- where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")";
68
- if (!compact && exception.mark.snippet) {
69
- where += `
70
-
71
- ` + exception.mark.snippet;
54
+ await copyFiles(bundledTemplatesDir, globalTemplatesDir);
55
+ const globalCommandsDir = join(homedir(), ".config", "opencode", "commands");
56
+ const bundledCommandsDir = join(bundledTemplatesDir, "commands");
57
+ if (existsSync(bundledCommandsDir)) {
58
+ await copyFiles(bundledCommandsDir, globalCommandsDir);
72
59
  }
73
- return message + " " + where;
60
+ await ctx.client.app.log({
61
+ body: {
62
+ service: "opencode-manifold",
63
+ level: "info",
64
+ message: "Global templates synchronized"
65
+ }
66
+ });
74
67
  }
75
- function YAMLException$1(reason, mark) {
76
- Error.call(this);
77
- this.name = "YAMLException";
78
- this.reason = reason;
79
- this.mark = mark;
80
- this.message = formatError(this, false);
81
- if (Error.captureStackTrace) {
82
- Error.captureStackTrace(this, this.constructor);
83
- } else {
84
- this.stack = new Error().stack || "";
68
+
69
+ // src/tools/dispatch-task.ts
70
+ import { tool } from "@opencode-ai/plugin";
71
+ import { readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
72
+ import { existsSync as existsSync5 } from "fs";
73
+ import { join as join5 } from "path";
74
+
75
+ // src/state-machine.ts
76
+ import { readFile as readFile3, writeFile as writeFile3, readdir as readdir2 } from "fs/promises";
77
+ import { existsSync as existsSync4 } from "fs";
78
+ import { join as join4 } from "path";
79
+
80
+ // src/session-spawner.ts
81
+ async function waitForSessionIdle(client, sessionId, timeoutMs) {
82
+ const startTime = Date.now();
83
+ while (Date.now() - startTime < timeoutMs) {
84
+ const statusResponse = await client.session.status({});
85
+ const statusData = statusResponse.data;
86
+ if (statusData && statusData[sessionId]) {
87
+ const status = statusData[sessionId];
88
+ if (status.type === "idle") {
89
+ return true;
90
+ }
91
+ if (status.type === "retry") {
92
+ const waitTime = status.next - Date.now();
93
+ if (waitTime > 0) {
94
+ await new Promise((resolve) => setTimeout(resolve, Math.min(waitTime, 1000)));
95
+ }
96
+ continue;
97
+ }
98
+ }
99
+ await new Promise((resolve) => setTimeout(resolve, 500));
85
100
  }
101
+ return false;
86
102
  }
87
- YAMLException$1.prototype = Object.create(Error.prototype);
88
- YAMLException$1.prototype.constructor = YAMLException$1;
89
- YAMLException$1.prototype.toString = function toString(compact) {
90
- return this.name + ": " + formatError(this, compact);
91
- };
92
- var exception = YAMLException$1;
93
- function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
94
- var head = "";
95
- var tail = "";
96
- var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
97
- if (position - lineStart > maxHalfLength) {
98
- head = " ... ";
99
- lineStart = position - maxHalfLength + head.length;
103
+ async function getLastAssistantMessage(client, sessionId) {
104
+ const messagesResponse = await client.session.messages({
105
+ path: { id: sessionId }
106
+ });
107
+ const messages = messagesResponse.data;
108
+ if (!messages || !Array.isArray(messages)) {
109
+ return "";
100
110
  }
101
- if (lineEnd - position > maxHalfLength) {
102
- tail = " ...";
103
- lineEnd = position + maxHalfLength - tail.length;
111
+ for (let i = messages.length - 1;i >= 0; i--) {
112
+ const msg = messages[i];
113
+ if (msg.info && msg.info.role === "assistant") {
114
+ if (msg.parts && Array.isArray(msg.parts)) {
115
+ for (const part of msg.parts) {
116
+ if (part.type === "text" && part.text) {
117
+ return part.text;
118
+ }
119
+ }
120
+ }
121
+ }
104
122
  }
105
- return {
106
- str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail,
107
- pos: position - lineStart + head.length
108
- };
123
+ return "";
109
124
  }
110
- function padStart(string, max) {
111
- return common.repeat(" ", max - string.length) + string;
125
+ async function cleanupSession(client, sessionId) {
126
+ try {
127
+ await client.session.delete({ path: { id: sessionId } });
128
+ } catch {}
112
129
  }
113
- function makeSnippet(mark, options) {
114
- options = Object.create(options || null);
115
- if (!mark.buffer)
116
- return null;
117
- if (!options.maxLength)
118
- options.maxLength = 79;
119
- if (typeof options.indent !== "number")
120
- options.indent = 1;
121
- if (typeof options.linesBefore !== "number")
122
- options.linesBefore = 3;
123
- if (typeof options.linesAfter !== "number")
124
- options.linesAfter = 2;
125
- var re = /\r?\n|\r|\0/g;
126
- var lineStarts = [0];
127
- var lineEnds = [];
128
- var match;
129
- var foundLineNo = -1;
130
- while (match = re.exec(mark.buffer)) {
131
- lineEnds.push(match.index);
132
- lineStarts.push(match.index + match[0].length);
133
- if (mark.position <= match.index && foundLineNo < 0) {
134
- foundLineNo = lineStarts.length - 2;
130
+ async function spawnSession(client, agent, prompt, timeoutSeconds) {
131
+ const timeoutMs = timeoutSeconds * 1000;
132
+ try {
133
+ const createResponse = await client.session.create({});
134
+ const session = createResponse.data;
135
+ if (!session || !session.id) {
136
+ return {
137
+ content: "",
138
+ success: false,
139
+ error: "Failed to create session"
140
+ };
135
141
  }
136
- }
137
- if (foundLineNo < 0)
138
- foundLineNo = lineStarts.length - 1;
139
- var result = "", i, line;
140
- var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
141
- var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
142
- for (i = 1;i <= options.linesBefore; i++) {
143
- if (foundLineNo - i < 0)
144
- break;
145
- line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);
146
- result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + `
147
- ` + result;
148
- }
149
- line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
150
- result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + `
151
- `;
152
- result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^" + `
153
- `;
154
- for (i = 1;i <= options.linesAfter; i++) {
155
- if (foundLineNo + i >= lineEnds.length)
156
- break;
157
- line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);
158
- result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + `
159
- `;
160
- }
161
- return result.replace(/\n$/, "");
162
- }
163
- var snippet = makeSnippet;
164
- var TYPE_CONSTRUCTOR_OPTIONS = [
165
- "kind",
166
- "multi",
167
- "resolve",
168
- "construct",
169
- "instanceOf",
170
- "predicate",
171
- "represent",
172
- "representName",
173
- "defaultStyle",
174
- "styleAliases"
175
- ];
176
- var YAML_NODE_KINDS = [
177
- "scalar",
178
- "sequence",
179
- "mapping"
180
- ];
181
- function compileStyleAliases(map) {
182
- var result = {};
183
- if (map !== null) {
184
- Object.keys(map).forEach(function(style) {
185
- map[style].forEach(function(alias) {
186
- result[String(alias)] = style;
187
- });
142
+ const sessionId = session.id;
143
+ await client.app.log({
144
+ body: {
145
+ service: "opencode-manifold",
146
+ level: "info",
147
+ message: `Created session ${sessionId} for agent ${agent}`
148
+ }
188
149
  });
189
- }
190
- return result;
191
- }
192
- function Type$1(tag, options) {
193
- options = options || {};
194
- Object.keys(options).forEach(function(name) {
195
- if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
196
- throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
150
+ try {
151
+ await client.session.promptAsync({
152
+ path: { id: sessionId },
153
+ body: {
154
+ agent,
155
+ noReply: true,
156
+ parts: [{ type: "text", text: prompt }]
157
+ }
158
+ });
159
+ const isIdle = await waitForSessionIdle(client, sessionId, timeoutMs);
160
+ if (!isIdle) {
161
+ await client.session.abort({ path: { id: sessionId } });
162
+ return {
163
+ content: "",
164
+ success: false,
165
+ error: `Session timed out after ${timeoutSeconds}s`
166
+ };
167
+ }
168
+ const content = await getLastAssistantMessage(client, sessionId);
169
+ await client.app.log({
170
+ body: {
171
+ service: "opencode-manifold",
172
+ level: "info",
173
+ message: `Session ${sessionId} completed, content length: ${content.length}`
174
+ }
175
+ });
176
+ return {
177
+ content,
178
+ success: true
179
+ };
180
+ } finally {
181
+ await cleanupSession(client, sessionId);
197
182
  }
198
- });
199
- this.options = options;
200
- this.tag = tag;
201
- this.kind = options["kind"] || null;
202
- this.resolve = options["resolve"] || function() {
203
- return true;
204
- };
205
- this.construct = options["construct"] || function(data) {
206
- return data;
207
- };
208
- this.instanceOf = options["instanceOf"] || null;
209
- this.predicate = options["predicate"] || null;
210
- this.represent = options["represent"] || null;
211
- this.representName = options["representName"] || null;
212
- this.defaultStyle = options["defaultStyle"] || null;
213
- this.multi = options["multi"] || false;
214
- this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
215
- if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
216
- throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
183
+ } catch (error) {
184
+ return {
185
+ content: "",
186
+ success: false,
187
+ error: error instanceof Error ? error.message : String(error)
188
+ };
217
189
  }
218
190
  }
219
- var type = Type$1;
220
- function compileList(schema, name) {
221
- var result = [];
222
- schema[name].forEach(function(currentType) {
223
- var newIndex = result.length;
224
- result.forEach(function(previousType, previousIndex) {
225
- if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
226
- newIndex = previousIndex;
227
- }
228
- });
229
- result[newIndex] = currentType;
191
+ async function spawnClerkSession(client, prompt, agent, timeout) {
192
+ await client.app.log({
193
+ body: {
194
+ service: "opencode-manifold",
195
+ level: "info",
196
+ message: `Spawning Clerk session (agent: ${agent}, timeout: ${timeout}s)`
197
+ }
230
198
  });
231
- return result;
199
+ return spawnSession(client, agent, prompt, timeout);
232
200
  }
233
- function compileMap() {
234
- var result = {
235
- scalar: {},
236
- sequence: {},
237
- mapping: {},
238
- fallback: {},
239
- multi: {
240
- scalar: [],
241
- sequence: [],
242
- mapping: [],
243
- fallback: []
244
- }
245
- }, index, length;
246
- function collectType(type2) {
247
- if (type2.multi) {
248
- result.multi[type2.kind].push(type2);
249
- result.multi["fallback"].push(type2);
250
- } else {
251
- result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
201
+ async function spawnSeniorDevSession(client, prompt, agent, timeout) {
202
+ await client.app.log({
203
+ body: {
204
+ service: "opencode-manifold",
205
+ level: "info",
206
+ message: `Spawning Senior Dev session (agent: ${agent}, timeout: ${timeout}s)`
252
207
  }
253
- }
254
- for (index = 0, length = arguments.length;index < length; index += 1) {
255
- arguments[index].forEach(collectType);
256
- }
257
- return result;
258
- }
259
- function Schema$1(definition) {
260
- return this.extend(definition);
208
+ });
209
+ return spawnSession(client, agent, prompt, timeout);
261
210
  }
262
- Schema$1.prototype.extend = function extend2(definition) {
263
- var implicit = [];
264
- var explicit = [];
265
- if (definition instanceof type) {
266
- explicit.push(definition);
267
- } else if (Array.isArray(definition)) {
268
- explicit = explicit.concat(definition);
269
- } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
270
- if (definition.implicit)
271
- implicit = implicit.concat(definition.implicit);
272
- if (definition.explicit)
273
- explicit = explicit.concat(definition.explicit);
274
- } else {
275
- throw new exception("Schema.extend argument should be a Type, [ Type ], " + "or a schema definition ({ implicit: [...], explicit: [...] })");
276
- }
277
- implicit.forEach(function(type$1) {
278
- if (!(type$1 instanceof type)) {
279
- throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
280
- }
281
- if (type$1.loadKind && type$1.loadKind !== "scalar") {
282
- throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
283
- }
284
- if (type$1.multi) {
285
- throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
211
+ async function spawnJuniorDevSession(client, prompt, seniorOutput, agent, timeout) {
212
+ await client.app.log({
213
+ body: {
214
+ service: "opencode-manifold",
215
+ level: "info",
216
+ message: `Spawning Junior Dev session (agent: ${agent}, timeout: ${timeout}s)`
286
217
  }
287
218
  });
288
- explicit.forEach(function(type$1) {
289
- if (!(type$1 instanceof type)) {
290
- throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
219
+ const fullPrompt = `${prompt}
220
+
221
+ ---
222
+
223
+ Senior Dev's Implementation:
224
+ ${seniorOutput}`;
225
+ return spawnSession(client, agent, fullPrompt, timeout);
226
+ }
227
+ async function spawnDebugSession(client, prompt, loopHistory, agent, timeout) {
228
+ await client.app.log({
229
+ body: {
230
+ service: "opencode-manifold",
231
+ level: "info",
232
+ message: `Spawning Debug session (agent: ${agent}, timeout: ${timeout}s)`
291
233
  }
292
234
  });
293
- var result = Object.create(Schema$1.prototype);
294
- result.implicit = (this.implicit || []).concat(implicit);
295
- result.explicit = (this.explicit || []).concat(explicit);
296
- result.compiledImplicit = compileList(result, "implicit");
297
- result.compiledExplicit = compileList(result, "explicit");
298
- result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
299
- return result;
300
- };
301
- var schema = Schema$1;
302
- var str = new type("tag:yaml.org,2002:str", {
303
- kind: "scalar",
304
- construct: function(data) {
305
- return data !== null ? data : "";
306
- }
307
- });
308
- var seq = new type("tag:yaml.org,2002:seq", {
309
- kind: "sequence",
310
- construct: function(data) {
311
- return data !== null ? data : [];
312
- }
313
- });
314
- var map = new type("tag:yaml.org,2002:map", {
315
- kind: "mapping",
316
- construct: function(data) {
317
- return data !== null ? data : {};
318
- }
319
- });
320
- var failsafe = new schema({
321
- explicit: [
322
- str,
323
- seq,
324
- map
325
- ]
326
- });
327
- function resolveYamlNull(data) {
328
- if (data === null)
329
- return true;
330
- var max = data.length;
331
- return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
235
+ const fullPrompt = `${prompt}
236
+
237
+ ---
238
+
239
+ Loop History:
240
+ ${loopHistory}`;
241
+ return spawnSession(client, agent, fullPrompt, timeout);
332
242
  }
333
- function constructYamlNull() {
334
- return null;
243
+ function parseJuniorFirstWord(response) {
244
+ const firstWord = response.trim().split(/\s+/)[0].toUpperCase();
245
+ if (firstWord === "COMPLETE") {
246
+ return "COMPLETE";
247
+ }
248
+ return "QUESTIONS";
335
249
  }
336
- function isNull(object) {
337
- return object === null;
250
+
251
+ // src/error-handler.ts
252
+ class ModelCallError extends Error {
253
+ agent;
254
+ attempt;
255
+ constructor(message, agent, attempt) {
256
+ super(message);
257
+ this.agent = agent;
258
+ this.attempt = attempt;
259
+ this.name = "ModelCallError";
260
+ }
338
261
  }
339
- var _null = new type("tag:yaml.org,2002:null", {
340
- kind: "scalar",
341
- resolve: resolveYamlNull,
342
- construct: constructYamlNull,
343
- predicate: isNull,
344
- represent: {
345
- canonical: function() {
346
- return "~";
347
- },
348
- lowercase: function() {
349
- return "null";
350
- },
351
- uppercase: function() {
352
- return "NULL";
353
- },
354
- camelcase: function() {
355
- return "Null";
356
- },
357
- empty: function() {
358
- return "";
262
+ async function retryWithBackoff(fn, options) {
263
+ let lastError;
264
+ for (let attempt = 0;attempt <= options.maxRetries; attempt++) {
265
+ try {
266
+ return await fn();
267
+ } catch (error) {
268
+ lastError = error instanceof Error ? error : new Error(String(error));
269
+ if (attempt < options.maxRetries) {
270
+ options.onRetry?.(attempt + 1, lastError);
271
+ const delay = Math.pow(2, attempt) * 100;
272
+ await new Promise((resolve) => setTimeout(resolve, delay));
273
+ }
359
274
  }
360
- },
361
- defaultStyle: "lowercase"
362
- });
363
- function resolveYamlBoolean(data) {
364
- if (data === null)
365
- return false;
366
- var max = data.length;
367
- return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
275
+ }
276
+ throw lastError;
368
277
  }
369
- function constructYamlBoolean(data) {
370
- return data === "true" || data === "True" || data === "TRUE";
278
+
279
+ // src/graph.ts
280
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
281
+ import { existsSync as existsSync2 } from "fs";
282
+ import { join as join2, dirname as dirname2 } from "path";
283
+
284
+ // node_modules/js-yaml/dist/js-yaml.mjs
285
+ /*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
286
+ function isNothing(subject) {
287
+ return typeof subject === "undefined" || subject === null;
371
288
  }
372
- function isBoolean(object) {
373
- return Object.prototype.toString.call(object) === "[object Boolean]";
289
+ function isObject(subject) {
290
+ return typeof subject === "object" && subject !== null;
374
291
  }
375
- var bool = new type("tag:yaml.org,2002:bool", {
376
- kind: "scalar",
377
- resolve: resolveYamlBoolean,
378
- construct: constructYamlBoolean,
379
- predicate: isBoolean,
380
- represent: {
381
- lowercase: function(object) {
382
- return object ? "true" : "false";
383
- },
384
- uppercase: function(object) {
385
- return object ? "TRUE" : "FALSE";
386
- },
387
- camelcase: function(object) {
388
- return object ? "True" : "False";
292
+ function toArray(sequence) {
293
+ if (Array.isArray(sequence))
294
+ return sequence;
295
+ else if (isNothing(sequence))
296
+ return [];
297
+ return [sequence];
298
+ }
299
+ function extend(target, source) {
300
+ var index, length, key, sourceKeys;
301
+ if (source) {
302
+ sourceKeys = Object.keys(source);
303
+ for (index = 0, length = sourceKeys.length;index < length; index += 1) {
304
+ key = sourceKeys[index];
305
+ target[key] = source[key];
389
306
  }
390
- },
391
- defaultStyle: "lowercase"
392
- });
393
- function isHexCode(c) {
394
- return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
307
+ }
308
+ return target;
395
309
  }
396
- function isOctCode(c) {
397
- return 48 <= c && c <= 55;
310
+ function repeat(string, count) {
311
+ var result = "", cycle;
312
+ for (cycle = 0;cycle < count; cycle += 1) {
313
+ result += string;
314
+ }
315
+ return result;
398
316
  }
399
- function isDecCode(c) {
400
- return 48 <= c && c <= 57;
317
+ function isNegativeZero(number) {
318
+ return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
401
319
  }
402
- function resolveYamlInteger(data) {
403
- if (data === null)
404
- return false;
405
- var max = data.length, index = 0, hasDigits = false, ch;
406
- if (!max)
407
- return false;
408
- ch = data[index];
409
- if (ch === "-" || ch === "+") {
410
- ch = data[++index];
411
- }
412
- if (ch === "0") {
413
- if (index + 1 === max)
414
- return true;
415
- ch = data[++index];
416
- if (ch === "b") {
417
- index++;
418
- for (;index < max; index++) {
419
- ch = data[index];
420
- if (ch === "_")
421
- continue;
422
- if (ch !== "0" && ch !== "1")
423
- return false;
424
- hasDigits = true;
425
- }
426
- return hasDigits && ch !== "_";
427
- }
428
- if (ch === "x") {
429
- index++;
430
- for (;index < max; index++) {
431
- ch = data[index];
432
- if (ch === "_")
433
- continue;
434
- if (!isHexCode(data.charCodeAt(index)))
435
- return false;
436
- hasDigits = true;
437
- }
438
- return hasDigits && ch !== "_";
439
- }
440
- if (ch === "o") {
441
- index++;
442
- for (;index < max; index++) {
443
- ch = data[index];
444
- if (ch === "_")
445
- continue;
446
- if (!isOctCode(data.charCodeAt(index)))
447
- return false;
448
- hasDigits = true;
449
- }
450
- return hasDigits && ch !== "_";
451
- }
320
+ var isNothing_1 = isNothing;
321
+ var isObject_1 = isObject;
322
+ var toArray_1 = toArray;
323
+ var repeat_1 = repeat;
324
+ var isNegativeZero_1 = isNegativeZero;
325
+ var extend_1 = extend;
326
+ var common = {
327
+ isNothing: isNothing_1,
328
+ isObject: isObject_1,
329
+ toArray: toArray_1,
330
+ repeat: repeat_1,
331
+ isNegativeZero: isNegativeZero_1,
332
+ extend: extend_1
333
+ };
334
+ function formatError(exception, compact) {
335
+ var where = "", message = exception.reason || "(unknown reason)";
336
+ if (!exception.mark)
337
+ return message;
338
+ if (exception.mark.name) {
339
+ where += 'in "' + exception.mark.name + '" ';
452
340
  }
453
- if (ch === "_")
454
- return false;
455
- for (;index < max; index++) {
456
- ch = data[index];
457
- if (ch === "_")
458
- continue;
459
- if (!isDecCode(data.charCodeAt(index))) {
460
- return false;
461
- }
462
- hasDigits = true;
341
+ where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")";
342
+ if (!compact && exception.mark.snippet) {
343
+ where += `
344
+
345
+ ` + exception.mark.snippet;
463
346
  }
464
- if (!hasDigits || ch === "_")
465
- return false;
466
- return true;
347
+ return message + " " + where;
467
348
  }
468
- function constructYamlInteger(data) {
469
- var value = data, sign = 1, ch;
470
- if (value.indexOf("_") !== -1) {
471
- value = value.replace(/_/g, "");
349
+ function YAMLException$1(reason, mark) {
350
+ Error.call(this);
351
+ this.name = "YAMLException";
352
+ this.reason = reason;
353
+ this.mark = mark;
354
+ this.message = formatError(this, false);
355
+ if (Error.captureStackTrace) {
356
+ Error.captureStackTrace(this, this.constructor);
357
+ } else {
358
+ this.stack = new Error().stack || "";
472
359
  }
473
- ch = value[0];
474
- if (ch === "-" || ch === "+") {
475
- if (ch === "-")
476
- sign = -1;
477
- value = value.slice(1);
478
- ch = value[0];
360
+ }
361
+ YAMLException$1.prototype = Object.create(Error.prototype);
362
+ YAMLException$1.prototype.constructor = YAMLException$1;
363
+ YAMLException$1.prototype.toString = function toString(compact) {
364
+ return this.name + ": " + formatError(this, compact);
365
+ };
366
+ var exception = YAMLException$1;
367
+ function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
368
+ var head = "";
369
+ var tail = "";
370
+ var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
371
+ if (position - lineStart > maxHalfLength) {
372
+ head = " ... ";
373
+ lineStart = position - maxHalfLength + head.length;
479
374
  }
480
- if (value === "0")
481
- return 0;
482
- if (ch === "0") {
483
- if (value[1] === "b")
484
- return sign * parseInt(value.slice(2), 2);
485
- if (value[1] === "x")
486
- return sign * parseInt(value.slice(2), 16);
487
- if (value[1] === "o")
488
- return sign * parseInt(value.slice(2), 8);
375
+ if (lineEnd - position > maxHalfLength) {
376
+ tail = " ...";
377
+ lineEnd = position + maxHalfLength - tail.length;
489
378
  }
490
- return sign * parseInt(value, 10);
379
+ return {
380
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail,
381
+ pos: position - lineStart + head.length
382
+ };
491
383
  }
492
- function isInteger(object) {
493
- return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
384
+ function padStart(string, max) {
385
+ return common.repeat(" ", max - string.length) + string;
494
386
  }
495
- var int = new type("tag:yaml.org,2002:int", {
496
- kind: "scalar",
497
- resolve: resolveYamlInteger,
498
- construct: constructYamlInteger,
499
- predicate: isInteger,
500
- represent: {
501
- binary: function(obj) {
502
- return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
503
- },
504
- octal: function(obj) {
505
- return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
506
- },
507
- decimal: function(obj) {
508
- return obj.toString(10);
509
- },
510
- hexadecimal: function(obj) {
511
- return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
387
+ function makeSnippet(mark, options) {
388
+ options = Object.create(options || null);
389
+ if (!mark.buffer)
390
+ return null;
391
+ if (!options.maxLength)
392
+ options.maxLength = 79;
393
+ if (typeof options.indent !== "number")
394
+ options.indent = 1;
395
+ if (typeof options.linesBefore !== "number")
396
+ options.linesBefore = 3;
397
+ if (typeof options.linesAfter !== "number")
398
+ options.linesAfter = 2;
399
+ var re = /\r?\n|\r|\0/g;
400
+ var lineStarts = [0];
401
+ var lineEnds = [];
402
+ var match;
403
+ var foundLineNo = -1;
404
+ while (match = re.exec(mark.buffer)) {
405
+ lineEnds.push(match.index);
406
+ lineStarts.push(match.index + match[0].length);
407
+ if (mark.position <= match.index && foundLineNo < 0) {
408
+ foundLineNo = lineStarts.length - 2;
512
409
  }
513
- },
514
- defaultStyle: "decimal",
515
- styleAliases: {
516
- binary: [2, "bin"],
517
- octal: [8, "oct"],
518
- decimal: [10, "dec"],
519
- hexadecimal: [16, "hex"]
520
410
  }
521
- });
522
- var YAML_FLOAT_PATTERN = new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?" + "|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?" + "|[-+]?\\.(?:inf|Inf|INF)" + "|\\.(?:nan|NaN|NAN))$");
523
- function resolveYamlFloat(data) {
524
- if (data === null)
525
- return false;
526
- if (!YAML_FLOAT_PATTERN.test(data) || data[data.length - 1] === "_") {
527
- return false;
411
+ if (foundLineNo < 0)
412
+ foundLineNo = lineStarts.length - 1;
413
+ var result = "", i, line;
414
+ var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
415
+ var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
416
+ for (i = 1;i <= options.linesBefore; i++) {
417
+ if (foundLineNo - i < 0)
418
+ break;
419
+ line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);
420
+ result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + `
421
+ ` + result;
528
422
  }
529
- return true;
530
- }
531
- function constructYamlFloat(data) {
532
- var value, sign;
533
- value = data.replace(/_/g, "").toLowerCase();
534
- sign = value[0] === "-" ? -1 : 1;
535
- if ("+-".indexOf(value[0]) >= 0) {
536
- value = value.slice(1);
423
+ line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
424
+ result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + `
425
+ `;
426
+ result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^" + `
427
+ `;
428
+ for (i = 1;i <= options.linesAfter; i++) {
429
+ if (foundLineNo + i >= lineEnds.length)
430
+ break;
431
+ line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);
432
+ result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + `
433
+ `;
537
434
  }
538
- if (value === ".inf") {
539
- return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
540
- } else if (value === ".nan") {
541
- return NaN;
435
+ return result.replace(/\n$/, "");
436
+ }
437
+ var snippet = makeSnippet;
438
+ var TYPE_CONSTRUCTOR_OPTIONS = [
439
+ "kind",
440
+ "multi",
441
+ "resolve",
442
+ "construct",
443
+ "instanceOf",
444
+ "predicate",
445
+ "represent",
446
+ "representName",
447
+ "defaultStyle",
448
+ "styleAliases"
449
+ ];
450
+ var YAML_NODE_KINDS = [
451
+ "scalar",
452
+ "sequence",
453
+ "mapping"
454
+ ];
455
+ function compileStyleAliases(map) {
456
+ var result = {};
457
+ if (map !== null) {
458
+ Object.keys(map).forEach(function(style) {
459
+ map[style].forEach(function(alias) {
460
+ result[String(alias)] = style;
461
+ });
462
+ });
542
463
  }
543
- return sign * parseFloat(value, 10);
464
+ return result;
544
465
  }
545
- var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
546
- function representYamlFloat(object, style) {
547
- var res;
548
- if (isNaN(object)) {
549
- switch (style) {
550
- case "lowercase":
551
- return ".nan";
552
- case "uppercase":
553
- return ".NAN";
554
- case "camelcase":
555
- return ".NaN";
466
+ function Type$1(tag, options) {
467
+ options = options || {};
468
+ Object.keys(options).forEach(function(name) {
469
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
470
+ throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
556
471
  }
557
- } else if (Number.POSITIVE_INFINITY === object) {
558
- switch (style) {
559
- case "lowercase":
560
- return ".inf";
561
- case "uppercase":
562
- return ".INF";
563
- case "camelcase":
564
- return ".Inf";
472
+ });
473
+ this.options = options;
474
+ this.tag = tag;
475
+ this.kind = options["kind"] || null;
476
+ this.resolve = options["resolve"] || function() {
477
+ return true;
478
+ };
479
+ this.construct = options["construct"] || function(data) {
480
+ return data;
481
+ };
482
+ this.instanceOf = options["instanceOf"] || null;
483
+ this.predicate = options["predicate"] || null;
484
+ this.represent = options["represent"] || null;
485
+ this.representName = options["representName"] || null;
486
+ this.defaultStyle = options["defaultStyle"] || null;
487
+ this.multi = options["multi"] || false;
488
+ this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
489
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
490
+ throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
491
+ }
492
+ }
493
+ var type = Type$1;
494
+ function compileList(schema, name) {
495
+ var result = [];
496
+ schema[name].forEach(function(currentType) {
497
+ var newIndex = result.length;
498
+ result.forEach(function(previousType, previousIndex) {
499
+ if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
500
+ newIndex = previousIndex;
501
+ }
502
+ });
503
+ result[newIndex] = currentType;
504
+ });
505
+ return result;
506
+ }
507
+ function compileMap() {
508
+ var result = {
509
+ scalar: {},
510
+ sequence: {},
511
+ mapping: {},
512
+ fallback: {},
513
+ multi: {
514
+ scalar: [],
515
+ sequence: [],
516
+ mapping: [],
517
+ fallback: []
565
518
  }
566
- } else if (Number.NEGATIVE_INFINITY === object) {
567
- switch (style) {
568
- case "lowercase":
569
- return "-.inf";
570
- case "uppercase":
571
- return "-.INF";
572
- case "camelcase":
573
- return "-.Inf";
519
+ }, index, length;
520
+ function collectType(type2) {
521
+ if (type2.multi) {
522
+ result.multi[type2.kind].push(type2);
523
+ result.multi["fallback"].push(type2);
524
+ } else {
525
+ result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
574
526
  }
575
- } else if (common.isNegativeZero(object)) {
576
- return "-0.0";
577
527
  }
578
- res = object.toString(10);
579
- return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
528
+ for (index = 0, length = arguments.length;index < length; index += 1) {
529
+ arguments[index].forEach(collectType);
530
+ }
531
+ return result;
580
532
  }
581
- function isFloat(object) {
582
- return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
533
+ function Schema$1(definition) {
534
+ return this.extend(definition);
583
535
  }
584
- var float = new type("tag:yaml.org,2002:float", {
536
+ Schema$1.prototype.extend = function extend2(definition) {
537
+ var implicit = [];
538
+ var explicit = [];
539
+ if (definition instanceof type) {
540
+ explicit.push(definition);
541
+ } else if (Array.isArray(definition)) {
542
+ explicit = explicit.concat(definition);
543
+ } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
544
+ if (definition.implicit)
545
+ implicit = implicit.concat(definition.implicit);
546
+ if (definition.explicit)
547
+ explicit = explicit.concat(definition.explicit);
548
+ } else {
549
+ throw new exception("Schema.extend argument should be a Type, [ Type ], " + "or a schema definition ({ implicit: [...], explicit: [...] })");
550
+ }
551
+ implicit.forEach(function(type$1) {
552
+ if (!(type$1 instanceof type)) {
553
+ throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
554
+ }
555
+ if (type$1.loadKind && type$1.loadKind !== "scalar") {
556
+ throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
557
+ }
558
+ if (type$1.multi) {
559
+ throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
560
+ }
561
+ });
562
+ explicit.forEach(function(type$1) {
563
+ if (!(type$1 instanceof type)) {
564
+ throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
565
+ }
566
+ });
567
+ var result = Object.create(Schema$1.prototype);
568
+ result.implicit = (this.implicit || []).concat(implicit);
569
+ result.explicit = (this.explicit || []).concat(explicit);
570
+ result.compiledImplicit = compileList(result, "implicit");
571
+ result.compiledExplicit = compileList(result, "explicit");
572
+ result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
573
+ return result;
574
+ };
575
+ var schema = Schema$1;
576
+ var str = new type("tag:yaml.org,2002:str", {
585
577
  kind: "scalar",
586
- resolve: resolveYamlFloat,
587
- construct: constructYamlFloat,
588
- predicate: isFloat,
589
- represent: representYamlFloat,
590
- defaultStyle: "lowercase"
578
+ construct: function(data) {
579
+ return data !== null ? data : "";
580
+ }
591
581
  });
592
- var json = failsafe.extend({
593
- implicit: [
594
- _null,
595
- bool,
596
- int,
597
- float
582
+ var seq = new type("tag:yaml.org,2002:seq", {
583
+ kind: "sequence",
584
+ construct: function(data) {
585
+ return data !== null ? data : [];
586
+ }
587
+ });
588
+ var map = new type("tag:yaml.org,2002:map", {
589
+ kind: "mapping",
590
+ construct: function(data) {
591
+ return data !== null ? data : {};
592
+ }
593
+ });
594
+ var failsafe = new schema({
595
+ explicit: [
596
+ str,
597
+ seq,
598
+ map
598
599
  ]
599
600
  });
600
- var core = json;
601
- var YAML_DATE_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9])" + "-([0-9][0-9])$");
602
- var YAML_TIMESTAMP_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9]?)" + "-([0-9][0-9]?)" + "(?:[Tt]|[ \\t]+)" + "([0-9][0-9]?)" + ":([0-9][0-9])" + ":([0-9][0-9])" + "(?:\\.([0-9]*))?" + "(?:[ \\t]*(Z|([-+])([0-9][0-9]?)" + "(?::([0-9][0-9]))?))?$");
603
- function resolveYamlTimestamp(data) {
601
+ function resolveYamlNull(data) {
604
602
  if (data === null)
605
- return false;
606
- if (YAML_DATE_REGEXP.exec(data) !== null)
607
603
  return true;
608
- if (YAML_TIMESTAMP_REGEXP.exec(data) !== null)
609
- return true;
610
- return false;
604
+ var max = data.length;
605
+ return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
611
606
  }
612
- function constructYamlTimestamp(data) {
613
- var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
614
- match = YAML_DATE_REGEXP.exec(data);
615
- if (match === null)
616
- match = YAML_TIMESTAMP_REGEXP.exec(data);
617
- if (match === null)
618
- throw new Error("Date resolve error");
619
- year = +match[1];
620
- month = +match[2] - 1;
621
- day = +match[3];
622
- if (!match[4]) {
623
- return new Date(Date.UTC(year, month, day));
624
- }
625
- hour = +match[4];
626
- minute = +match[5];
627
- second = +match[6];
628
- if (match[7]) {
629
- fraction = match[7].slice(0, 3);
630
- while (fraction.length < 3) {
631
- fraction += "0";
632
- }
633
- fraction = +fraction;
634
- }
635
- if (match[9]) {
636
- tz_hour = +match[10];
637
- tz_minute = +(match[11] || 0);
638
- delta = (tz_hour * 60 + tz_minute) * 60000;
639
- if (match[9] === "-")
640
- delta = -delta;
641
- }
642
- date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
643
- if (delta)
644
- date.setTime(date.getTime() - delta);
645
- return date;
607
+ function constructYamlNull() {
608
+ return null;
646
609
  }
647
- function representYamlTimestamp(object) {
648
- return object.toISOString();
610
+ function isNull(object) {
611
+ return object === null;
649
612
  }
650
- var timestamp = new type("tag:yaml.org,2002:timestamp", {
613
+ var _null = new type("tag:yaml.org,2002:null", {
651
614
  kind: "scalar",
652
- resolve: resolveYamlTimestamp,
653
- construct: constructYamlTimestamp,
654
- instanceOf: Date,
655
- represent: representYamlTimestamp
615
+ resolve: resolveYamlNull,
616
+ construct: constructYamlNull,
617
+ predicate: isNull,
618
+ represent: {
619
+ canonical: function() {
620
+ return "~";
621
+ },
622
+ lowercase: function() {
623
+ return "null";
624
+ },
625
+ uppercase: function() {
626
+ return "NULL";
627
+ },
628
+ camelcase: function() {
629
+ return "Null";
630
+ },
631
+ empty: function() {
632
+ return "";
633
+ }
634
+ },
635
+ defaultStyle: "lowercase"
656
636
  });
657
- function resolveYamlMerge(data) {
658
- return data === "<<" || data === null;
637
+ function resolveYamlBoolean(data) {
638
+ if (data === null)
639
+ return false;
640
+ var max = data.length;
641
+ return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
659
642
  }
660
- var merge = new type("tag:yaml.org,2002:merge", {
643
+ function constructYamlBoolean(data) {
644
+ return data === "true" || data === "True" || data === "TRUE";
645
+ }
646
+ function isBoolean(object) {
647
+ return Object.prototype.toString.call(object) === "[object Boolean]";
648
+ }
649
+ var bool = new type("tag:yaml.org,2002:bool", {
661
650
  kind: "scalar",
662
- resolve: resolveYamlMerge
651
+ resolve: resolveYamlBoolean,
652
+ construct: constructYamlBoolean,
653
+ predicate: isBoolean,
654
+ represent: {
655
+ lowercase: function(object) {
656
+ return object ? "true" : "false";
657
+ },
658
+ uppercase: function(object) {
659
+ return object ? "TRUE" : "FALSE";
660
+ },
661
+ camelcase: function(object) {
662
+ return object ? "True" : "False";
663
+ }
664
+ },
665
+ defaultStyle: "lowercase"
663
666
  });
664
- var BASE64_MAP = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
665
- \r`;
666
- function resolveYamlBinary(data) {
667
+ function isHexCode(c) {
668
+ return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
669
+ }
670
+ function isOctCode(c) {
671
+ return 48 <= c && c <= 55;
672
+ }
673
+ function isDecCode(c) {
674
+ return 48 <= c && c <= 57;
675
+ }
676
+ function resolveYamlInteger(data) {
667
677
  if (data === null)
668
678
  return false;
669
- var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP;
670
- for (idx = 0;idx < max; idx++) {
671
- code = map2.indexOf(data.charAt(idx));
672
- if (code > 64)
679
+ var max = data.length, index = 0, hasDigits = false, ch;
680
+ if (!max)
681
+ return false;
682
+ ch = data[index];
683
+ if (ch === "-" || ch === "+") {
684
+ ch = data[++index];
685
+ }
686
+ if (ch === "0") {
687
+ if (index + 1 === max)
688
+ return true;
689
+ ch = data[++index];
690
+ if (ch === "b") {
691
+ index++;
692
+ for (;index < max; index++) {
693
+ ch = data[index];
694
+ if (ch === "_")
695
+ continue;
696
+ if (ch !== "0" && ch !== "1")
697
+ return false;
698
+ hasDigits = true;
699
+ }
700
+ return hasDigits && ch !== "_";
701
+ }
702
+ if (ch === "x") {
703
+ index++;
704
+ for (;index < max; index++) {
705
+ ch = data[index];
706
+ if (ch === "_")
707
+ continue;
708
+ if (!isHexCode(data.charCodeAt(index)))
709
+ return false;
710
+ hasDigits = true;
711
+ }
712
+ return hasDigits && ch !== "_";
713
+ }
714
+ if (ch === "o") {
715
+ index++;
716
+ for (;index < max; index++) {
717
+ ch = data[index];
718
+ if (ch === "_")
719
+ continue;
720
+ if (!isOctCode(data.charCodeAt(index)))
721
+ return false;
722
+ hasDigits = true;
723
+ }
724
+ return hasDigits && ch !== "_";
725
+ }
726
+ }
727
+ if (ch === "_")
728
+ return false;
729
+ for (;index < max; index++) {
730
+ ch = data[index];
731
+ if (ch === "_")
673
732
  continue;
674
- if (code < 0)
733
+ if (!isDecCode(data.charCodeAt(index))) {
675
734
  return false;
676
- bitlen += 6;
735
+ }
736
+ hasDigits = true;
677
737
  }
678
- return bitlen % 8 === 0;
738
+ if (!hasDigits || ch === "_")
739
+ return false;
740
+ return true;
679
741
  }
680
- function constructYamlBinary(data) {
681
- var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = [];
682
- for (idx = 0;idx < max; idx++) {
683
- if (idx % 4 === 0 && idx) {
684
- result.push(bits >> 16 & 255);
685
- result.push(bits >> 8 & 255);
686
- result.push(bits & 255);
687
- }
688
- bits = bits << 6 | map2.indexOf(input.charAt(idx));
742
+ function constructYamlInteger(data) {
743
+ var value = data, sign = 1, ch;
744
+ if (value.indexOf("_") !== -1) {
745
+ value = value.replace(/_/g, "");
689
746
  }
690
- tailbits = max % 4 * 6;
691
- if (tailbits === 0) {
692
- result.push(bits >> 16 & 255);
693
- result.push(bits >> 8 & 255);
694
- result.push(bits & 255);
695
- } else if (tailbits === 18) {
696
- result.push(bits >> 10 & 255);
697
- result.push(bits >> 2 & 255);
698
- } else if (tailbits === 12) {
699
- result.push(bits >> 4 & 255);
747
+ ch = value[0];
748
+ if (ch === "-" || ch === "+") {
749
+ if (ch === "-")
750
+ sign = -1;
751
+ value = value.slice(1);
752
+ ch = value[0];
700
753
  }
701
- return new Uint8Array(result);
754
+ if (value === "0")
755
+ return 0;
756
+ if (ch === "0") {
757
+ if (value[1] === "b")
758
+ return sign * parseInt(value.slice(2), 2);
759
+ if (value[1] === "x")
760
+ return sign * parseInt(value.slice(2), 16);
761
+ if (value[1] === "o")
762
+ return sign * parseInt(value.slice(2), 8);
763
+ }
764
+ return sign * parseInt(value, 10);
702
765
  }
703
- function representYamlBinary(object) {
704
- var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP;
705
- for (idx = 0;idx < max; idx++) {
706
- if (idx % 3 === 0 && idx) {
707
- result += map2[bits >> 18 & 63];
766
+ function isInteger(object) {
767
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
768
+ }
769
+ var int = new type("tag:yaml.org,2002:int", {
770
+ kind: "scalar",
771
+ resolve: resolveYamlInteger,
772
+ construct: constructYamlInteger,
773
+ predicate: isInteger,
774
+ represent: {
775
+ binary: function(obj) {
776
+ return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
777
+ },
778
+ octal: function(obj) {
779
+ return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
780
+ },
781
+ decimal: function(obj) {
782
+ return obj.toString(10);
783
+ },
784
+ hexadecimal: function(obj) {
785
+ return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
786
+ }
787
+ },
788
+ defaultStyle: "decimal",
789
+ styleAliases: {
790
+ binary: [2, "bin"],
791
+ octal: [8, "oct"],
792
+ decimal: [10, "dec"],
793
+ hexadecimal: [16, "hex"]
794
+ }
795
+ });
796
+ var YAML_FLOAT_PATTERN = new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?" + "|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?" + "|[-+]?\\.(?:inf|Inf|INF)" + "|\\.(?:nan|NaN|NAN))$");
797
+ function resolveYamlFloat(data) {
798
+ if (data === null)
799
+ return false;
800
+ if (!YAML_FLOAT_PATTERN.test(data) || data[data.length - 1] === "_") {
801
+ return false;
802
+ }
803
+ return true;
804
+ }
805
+ function constructYamlFloat(data) {
806
+ var value, sign;
807
+ value = data.replace(/_/g, "").toLowerCase();
808
+ sign = value[0] === "-" ? -1 : 1;
809
+ if ("+-".indexOf(value[0]) >= 0) {
810
+ value = value.slice(1);
811
+ }
812
+ if (value === ".inf") {
813
+ return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
814
+ } else if (value === ".nan") {
815
+ return NaN;
816
+ }
817
+ return sign * parseFloat(value, 10);
818
+ }
819
+ var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
820
+ function representYamlFloat(object, style) {
821
+ var res;
822
+ if (isNaN(object)) {
823
+ switch (style) {
824
+ case "lowercase":
825
+ return ".nan";
826
+ case "uppercase":
827
+ return ".NAN";
828
+ case "camelcase":
829
+ return ".NaN";
830
+ }
831
+ } else if (Number.POSITIVE_INFINITY === object) {
832
+ switch (style) {
833
+ case "lowercase":
834
+ return ".inf";
835
+ case "uppercase":
836
+ return ".INF";
837
+ case "camelcase":
838
+ return ".Inf";
839
+ }
840
+ } else if (Number.NEGATIVE_INFINITY === object) {
841
+ switch (style) {
842
+ case "lowercase":
843
+ return "-.inf";
844
+ case "uppercase":
845
+ return "-.INF";
846
+ case "camelcase":
847
+ return "-.Inf";
848
+ }
849
+ } else if (common.isNegativeZero(object)) {
850
+ return "-0.0";
851
+ }
852
+ res = object.toString(10);
853
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
854
+ }
855
+ function isFloat(object) {
856
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
857
+ }
858
+ var float = new type("tag:yaml.org,2002:float", {
859
+ kind: "scalar",
860
+ resolve: resolveYamlFloat,
861
+ construct: constructYamlFloat,
862
+ predicate: isFloat,
863
+ represent: representYamlFloat,
864
+ defaultStyle: "lowercase"
865
+ });
866
+ var json = failsafe.extend({
867
+ implicit: [
868
+ _null,
869
+ bool,
870
+ int,
871
+ float
872
+ ]
873
+ });
874
+ var core = json;
875
+ var YAML_DATE_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9])" + "-([0-9][0-9])$");
876
+ var YAML_TIMESTAMP_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9]?)" + "-([0-9][0-9]?)" + "(?:[Tt]|[ \\t]+)" + "([0-9][0-9]?)" + ":([0-9][0-9])" + ":([0-9][0-9])" + "(?:\\.([0-9]*))?" + "(?:[ \\t]*(Z|([-+])([0-9][0-9]?)" + "(?::([0-9][0-9]))?))?$");
877
+ function resolveYamlTimestamp(data) {
878
+ if (data === null)
879
+ return false;
880
+ if (YAML_DATE_REGEXP.exec(data) !== null)
881
+ return true;
882
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null)
883
+ return true;
884
+ return false;
885
+ }
886
+ function constructYamlTimestamp(data) {
887
+ var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
888
+ match = YAML_DATE_REGEXP.exec(data);
889
+ if (match === null)
890
+ match = YAML_TIMESTAMP_REGEXP.exec(data);
891
+ if (match === null)
892
+ throw new Error("Date resolve error");
893
+ year = +match[1];
894
+ month = +match[2] - 1;
895
+ day = +match[3];
896
+ if (!match[4]) {
897
+ return new Date(Date.UTC(year, month, day));
898
+ }
899
+ hour = +match[4];
900
+ minute = +match[5];
901
+ second = +match[6];
902
+ if (match[7]) {
903
+ fraction = match[7].slice(0, 3);
904
+ while (fraction.length < 3) {
905
+ fraction += "0";
906
+ }
907
+ fraction = +fraction;
908
+ }
909
+ if (match[9]) {
910
+ tz_hour = +match[10];
911
+ tz_minute = +(match[11] || 0);
912
+ delta = (tz_hour * 60 + tz_minute) * 60000;
913
+ if (match[9] === "-")
914
+ delta = -delta;
915
+ }
916
+ date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
917
+ if (delta)
918
+ date.setTime(date.getTime() - delta);
919
+ return date;
920
+ }
921
+ function representYamlTimestamp(object) {
922
+ return object.toISOString();
923
+ }
924
+ var timestamp = new type("tag:yaml.org,2002:timestamp", {
925
+ kind: "scalar",
926
+ resolve: resolveYamlTimestamp,
927
+ construct: constructYamlTimestamp,
928
+ instanceOf: Date,
929
+ represent: representYamlTimestamp
930
+ });
931
+ function resolveYamlMerge(data) {
932
+ return data === "<<" || data === null;
933
+ }
934
+ var merge = new type("tag:yaml.org,2002:merge", {
935
+ kind: "scalar",
936
+ resolve: resolveYamlMerge
937
+ });
938
+ var BASE64_MAP = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
939
+ \r`;
940
+ function resolveYamlBinary(data) {
941
+ if (data === null)
942
+ return false;
943
+ var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP;
944
+ for (idx = 0;idx < max; idx++) {
945
+ code = map2.indexOf(data.charAt(idx));
946
+ if (code > 64)
947
+ continue;
948
+ if (code < 0)
949
+ return false;
950
+ bitlen += 6;
951
+ }
952
+ return bitlen % 8 === 0;
953
+ }
954
+ function constructYamlBinary(data) {
955
+ var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = [];
956
+ for (idx = 0;idx < max; idx++) {
957
+ if (idx % 4 === 0 && idx) {
958
+ result.push(bits >> 16 & 255);
959
+ result.push(bits >> 8 & 255);
960
+ result.push(bits & 255);
961
+ }
962
+ bits = bits << 6 | map2.indexOf(input.charAt(idx));
963
+ }
964
+ tailbits = max % 4 * 6;
965
+ if (tailbits === 0) {
966
+ result.push(bits >> 16 & 255);
967
+ result.push(bits >> 8 & 255);
968
+ result.push(bits & 255);
969
+ } else if (tailbits === 18) {
970
+ result.push(bits >> 10 & 255);
971
+ result.push(bits >> 2 & 255);
972
+ } else if (tailbits === 12) {
973
+ result.push(bits >> 4 & 255);
974
+ }
975
+ return new Uint8Array(result);
976
+ }
977
+ function representYamlBinary(object) {
978
+ var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP;
979
+ for (idx = 0;idx < max; idx++) {
980
+ if (idx % 3 === 0 && idx) {
981
+ result += map2[bits >> 18 & 63];
708
982
  result += map2[bits >> 12 & 63];
709
983
  result += map2[bits >> 6 & 63];
710
984
  result += map2[bits & 63];
@@ -2071,1220 +2345,628 @@ var DEPRECATED_BOOLEANS_SYNTAX = [
2071
2345
  "NO",
2072
2346
  "off",
2073
2347
  "Off",
2074
- "OFF"
2075
- ];
2076
- var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
2077
- function compileStyleMap(schema2, map2) {
2078
- var result, keys, index, length, tag, style, type2;
2079
- if (map2 === null)
2080
- return {};
2081
- result = {};
2082
- keys = Object.keys(map2);
2083
- for (index = 0, length = keys.length;index < length; index += 1) {
2084
- tag = keys[index];
2085
- style = String(map2[tag]);
2086
- if (tag.slice(0, 2) === "!!") {
2087
- tag = "tag:yaml.org,2002:" + tag.slice(2);
2088
- }
2089
- type2 = schema2.compiledTypeMap["fallback"][tag];
2090
- if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
2091
- style = type2.styleAliases[style];
2092
- }
2093
- result[tag] = style;
2094
- }
2095
- return result;
2096
- }
2097
- function encodeHex(character) {
2098
- var string, handle, length;
2099
- string = character.toString(16).toUpperCase();
2100
- if (character <= 255) {
2101
- handle = "x";
2102
- length = 2;
2103
- } else if (character <= 65535) {
2104
- handle = "u";
2105
- length = 4;
2106
- } else if (character <= 4294967295) {
2107
- handle = "U";
2108
- length = 8;
2109
- } else {
2110
- throw new exception("code point within a string may not be greater than 0xFFFFFFFF");
2111
- }
2112
- return "\\" + handle + common.repeat("0", length - string.length) + string;
2113
- }
2114
- var QUOTING_TYPE_SINGLE = 1;
2115
- var QUOTING_TYPE_DOUBLE = 2;
2116
- function State(options) {
2117
- this.schema = options["schema"] || _default;
2118
- this.indent = Math.max(1, options["indent"] || 2);
2119
- this.noArrayIndent = options["noArrayIndent"] || false;
2120
- this.skipInvalid = options["skipInvalid"] || false;
2121
- this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
2122
- this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
2123
- this.sortKeys = options["sortKeys"] || false;
2124
- this.lineWidth = options["lineWidth"] || 80;
2125
- this.noRefs = options["noRefs"] || false;
2126
- this.noCompatMode = options["noCompatMode"] || false;
2127
- this.condenseFlow = options["condenseFlow"] || false;
2128
- this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
2129
- this.forceQuotes = options["forceQuotes"] || false;
2130
- this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
2131
- this.implicitTypes = this.schema.compiledImplicit;
2132
- this.explicitTypes = this.schema.compiledExplicit;
2133
- this.tag = null;
2134
- this.result = "";
2135
- this.duplicates = [];
2136
- this.usedDuplicates = null;
2137
- }
2138
- function indentString(string, spaces) {
2139
- var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string.length;
2140
- while (position < length) {
2141
- next = string.indexOf(`
2142
- `, position);
2143
- if (next === -1) {
2144
- line = string.slice(position);
2145
- position = length;
2146
- } else {
2147
- line = string.slice(position, next + 1);
2148
- position = next + 1;
2149
- }
2150
- if (line.length && line !== `
2151
- `)
2152
- result += ind;
2153
- result += line;
2154
- }
2155
- return result;
2156
- }
2157
- function generateNextLine(state, level) {
2158
- return `
2159
- ` + common.repeat(" ", state.indent * level);
2160
- }
2161
- function testImplicitResolving(state, str2) {
2162
- var index, length, type2;
2163
- for (index = 0, length = state.implicitTypes.length;index < length; index += 1) {
2164
- type2 = state.implicitTypes[index];
2165
- if (type2.resolve(str2)) {
2166
- return true;
2167
- }
2168
- }
2169
- return false;
2170
- }
2171
- function isWhitespace(c) {
2172
- return c === CHAR_SPACE || c === CHAR_TAB;
2173
- }
2174
- function isPrintable(c) {
2175
- return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;
2176
- }
2177
- function isNsCharOrWhitespace(c) {
2178
- return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
2179
- }
2180
- function isPlainSafe(c, prev, inblock) {
2181
- var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
2182
- var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
2183
- return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar;
2184
- }
2185
- function isPlainSafeFirst(c) {
2186
- return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
2187
- }
2188
- function isPlainSafeLast(c) {
2189
- return !isWhitespace(c) && c !== CHAR_COLON;
2190
- }
2191
- function codePointAt(string, pos) {
2192
- var first = string.charCodeAt(pos), second;
2193
- if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
2194
- second = string.charCodeAt(pos + 1);
2195
- if (second >= 56320 && second <= 57343) {
2196
- return (first - 55296) * 1024 + second - 56320 + 65536;
2197
- }
2198
- }
2199
- return first;
2200
- }
2201
- function needIndentIndicator(string) {
2202
- var leadingSpaceRe = /^\n* /;
2203
- return leadingSpaceRe.test(string);
2204
- }
2205
- var STYLE_PLAIN = 1;
2206
- var STYLE_SINGLE = 2;
2207
- var STYLE_LITERAL = 3;
2208
- var STYLE_FOLDED = 4;
2209
- var STYLE_DOUBLE = 5;
2210
- function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
2211
- var i2;
2212
- var char = 0;
2213
- var prevChar = null;
2214
- var hasLineBreak = false;
2215
- var hasFoldableLine = false;
2216
- var shouldTrackWidth = lineWidth !== -1;
2217
- var previousLineBreak = -1;
2218
- var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
2219
- if (singleLineOnly || forceQuotes) {
2220
- for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2221
- char = codePointAt(string, i2);
2222
- if (!isPrintable(char)) {
2223
- return STYLE_DOUBLE;
2224
- }
2225
- plain = plain && isPlainSafe(char, prevChar, inblock);
2226
- prevChar = char;
2227
- }
2228
- } else {
2229
- for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2230
- char = codePointAt(string, i2);
2231
- if (char === CHAR_LINE_FEED) {
2232
- hasLineBreak = true;
2233
- if (shouldTrackWidth) {
2234
- hasFoldableLine = hasFoldableLine || i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
2235
- previousLineBreak = i2;
2236
- }
2237
- } else if (!isPrintable(char)) {
2238
- return STYLE_DOUBLE;
2239
- }
2240
- plain = plain && isPlainSafe(char, prevChar, inblock);
2241
- prevChar = char;
2242
- }
2243
- hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
2244
- }
2245
- if (!hasLineBreak && !hasFoldableLine) {
2246
- if (plain && !forceQuotes && !testAmbiguousType(string)) {
2247
- return STYLE_PLAIN;
2248
- }
2249
- return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2250
- }
2251
- if (indentPerLevel > 9 && needIndentIndicator(string)) {
2252
- return STYLE_DOUBLE;
2253
- }
2254
- if (!forceQuotes) {
2255
- return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
2256
- }
2257
- return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2258
- }
2259
- function writeScalar(state, string, level, iskey, inblock) {
2260
- state.dump = function() {
2261
- if (string.length === 0) {
2262
- return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
2263
- }
2264
- if (!state.noCompatMode) {
2265
- if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
2266
- return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
2267
- }
2268
- }
2269
- var indent = state.indent * Math.max(1, level);
2270
- var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
2271
- var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
2272
- function testAmbiguity(string2) {
2273
- return testImplicitResolving(state, string2);
2274
- }
2275
- switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
2276
- case STYLE_PLAIN:
2277
- return string;
2278
- case STYLE_SINGLE:
2279
- return "'" + string.replace(/'/g, "''") + "'";
2280
- case STYLE_LITERAL:
2281
- return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
2282
- case STYLE_FOLDED:
2283
- return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
2284
- case STYLE_DOUBLE:
2285
- return '"' + escapeString(string) + '"';
2286
- default:
2287
- throw new exception("impossible error: invalid scalar style");
2288
- }
2289
- }();
2290
- }
2291
- function blockHeader(string, indentPerLevel) {
2292
- var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
2293
- var clip = string[string.length - 1] === `
2294
- `;
2295
- var keep = clip && (string[string.length - 2] === `
2296
- ` || string === `
2297
- `);
2298
- var chomp = keep ? "+" : clip ? "" : "-";
2299
- return indentIndicator + chomp + `
2300
- `;
2301
- }
2302
- function dropEndingNewline(string) {
2303
- return string[string.length - 1] === `
2304
- ` ? string.slice(0, -1) : string;
2305
- }
2306
- function foldString(string, width) {
2307
- var lineRe = /(\n+)([^\n]*)/g;
2308
- var result = function() {
2309
- var nextLF = string.indexOf(`
2310
- `);
2311
- nextLF = nextLF !== -1 ? nextLF : string.length;
2312
- lineRe.lastIndex = nextLF;
2313
- return foldLine(string.slice(0, nextLF), width);
2314
- }();
2315
- var prevMoreIndented = string[0] === `
2316
- ` || string[0] === " ";
2317
- var moreIndented;
2318
- var match;
2319
- while (match = lineRe.exec(string)) {
2320
- var prefix = match[1], line = match[2];
2321
- moreIndented = line[0] === " ";
2322
- result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? `
2323
- ` : "") + foldLine(line, width);
2324
- prevMoreIndented = moreIndented;
2325
- }
2326
- return result;
2327
- }
2328
- function foldLine(line, width) {
2329
- if (line === "" || line[0] === " ")
2330
- return line;
2331
- var breakRe = / [^ ]/g;
2332
- var match;
2333
- var start = 0, end, curr = 0, next = 0;
2334
- var result = "";
2335
- while (match = breakRe.exec(line)) {
2336
- next = match.index;
2337
- if (next - start > width) {
2338
- end = curr > start ? curr : next;
2339
- result += `
2340
- ` + line.slice(start, end);
2341
- start = end + 1;
2342
- }
2343
- curr = next;
2344
- }
2345
- result += `
2346
- `;
2347
- if (line.length - start > width && curr > start) {
2348
- result += line.slice(start, curr) + `
2349
- ` + line.slice(curr + 1);
2350
- } else {
2351
- result += line.slice(start);
2352
- }
2353
- return result.slice(1);
2354
- }
2355
- function escapeString(string) {
2356
- var result = "";
2357
- var char = 0;
2358
- var escapeSeq;
2359
- for (var i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2360
- char = codePointAt(string, i2);
2361
- escapeSeq = ESCAPE_SEQUENCES[char];
2362
- if (!escapeSeq && isPrintable(char)) {
2363
- result += string[i2];
2364
- if (char >= 65536)
2365
- result += string[i2 + 1];
2366
- } else {
2367
- result += escapeSeq || encodeHex(char);
2368
- }
2369
- }
2370
- return result;
2371
- }
2372
- function writeFlowSequence(state, level, object) {
2373
- var _result = "", _tag = state.tag, index, length, value;
2374
- for (index = 0, length = object.length;index < length; index += 1) {
2375
- value = object[index];
2376
- if (state.replacer) {
2377
- value = state.replacer.call(object, String(index), value);
2378
- }
2379
- if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
2380
- if (_result !== "")
2381
- _result += "," + (!state.condenseFlow ? " " : "");
2382
- _result += state.dump;
2383
- }
2384
- }
2385
- state.tag = _tag;
2386
- state.dump = "[" + _result + "]";
2387
- }
2388
- function writeBlockSequence(state, level, object, compact) {
2389
- var _result = "", _tag = state.tag, index, length, value;
2390
- for (index = 0, length = object.length;index < length; index += 1) {
2391
- value = object[index];
2392
- if (state.replacer) {
2393
- value = state.replacer.call(object, String(index), value);
2394
- }
2395
- if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
2396
- if (!compact || _result !== "") {
2397
- _result += generateNextLine(state, level);
2398
- }
2399
- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2400
- _result += "-";
2401
- } else {
2402
- _result += "- ";
2403
- }
2404
- _result += state.dump;
2405
- }
2406
- }
2407
- state.tag = _tag;
2408
- state.dump = _result || "[]";
2409
- }
2410
- function writeFlowMapping(state, level, object) {
2411
- var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;
2412
- for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2413
- pairBuffer = "";
2414
- if (_result !== "")
2415
- pairBuffer += ", ";
2416
- if (state.condenseFlow)
2417
- pairBuffer += '"';
2418
- objectKey = objectKeyList[index];
2419
- objectValue = object[objectKey];
2420
- if (state.replacer) {
2421
- objectValue = state.replacer.call(object, objectKey, objectValue);
2422
- }
2423
- if (!writeNode(state, level, objectKey, false, false)) {
2424
- continue;
2425
- }
2426
- if (state.dump.length > 1024)
2427
- pairBuffer += "? ";
2428
- pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
2429
- if (!writeNode(state, level, objectValue, false, false)) {
2430
- continue;
2431
- }
2432
- pairBuffer += state.dump;
2433
- _result += pairBuffer;
2434
- }
2435
- state.tag = _tag;
2436
- state.dump = "{" + _result + "}";
2437
- }
2438
- function writeBlockMapping(state, level, object, compact) {
2439
- var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;
2440
- if (state.sortKeys === true) {
2441
- objectKeyList.sort();
2442
- } else if (typeof state.sortKeys === "function") {
2443
- objectKeyList.sort(state.sortKeys);
2444
- } else if (state.sortKeys) {
2445
- throw new exception("sortKeys must be a boolean or a function");
2446
- }
2447
- for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2448
- pairBuffer = "";
2449
- if (!compact || _result !== "") {
2450
- pairBuffer += generateNextLine(state, level);
2451
- }
2452
- objectKey = objectKeyList[index];
2453
- objectValue = object[objectKey];
2454
- if (state.replacer) {
2455
- objectValue = state.replacer.call(object, objectKey, objectValue);
2456
- }
2457
- if (!writeNode(state, level + 1, objectKey, true, true, true)) {
2458
- continue;
2459
- }
2460
- explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
2461
- if (explicitPair) {
2462
- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2463
- pairBuffer += "?";
2464
- } else {
2465
- pairBuffer += "? ";
2466
- }
2467
- }
2468
- pairBuffer += state.dump;
2469
- if (explicitPair) {
2470
- pairBuffer += generateNextLine(state, level);
2471
- }
2472
- if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
2473
- continue;
2474
- }
2475
- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2476
- pairBuffer += ":";
2477
- } else {
2478
- pairBuffer += ": ";
2479
- }
2480
- pairBuffer += state.dump;
2481
- _result += pairBuffer;
2482
- }
2483
- state.tag = _tag;
2484
- state.dump = _result || "{}";
2485
- }
2486
- function detectType(state, object, explicit) {
2487
- var _result, typeList, index, length, type2, style;
2488
- typeList = explicit ? state.explicitTypes : state.implicitTypes;
2489
- for (index = 0, length = typeList.length;index < length; index += 1) {
2490
- type2 = typeList[index];
2491
- if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
2492
- if (explicit) {
2493
- if (type2.multi && type2.representName) {
2494
- state.tag = type2.representName(object);
2495
- } else {
2496
- state.tag = type2.tag;
2497
- }
2498
- } else {
2499
- state.tag = "?";
2500
- }
2501
- if (type2.represent) {
2502
- style = state.styleMap[type2.tag] || type2.defaultStyle;
2503
- if (_toString.call(type2.represent) === "[object Function]") {
2504
- _result = type2.represent(object, style);
2505
- } else if (_hasOwnProperty.call(type2.represent, style)) {
2506
- _result = type2.represent[style](object, style);
2507
- } else {
2508
- throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
2509
- }
2510
- state.dump = _result;
2511
- }
2512
- return true;
2348
+ "OFF"
2349
+ ];
2350
+ var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
2351
+ function compileStyleMap(schema2, map2) {
2352
+ var result, keys, index, length, tag, style, type2;
2353
+ if (map2 === null)
2354
+ return {};
2355
+ result = {};
2356
+ keys = Object.keys(map2);
2357
+ for (index = 0, length = keys.length;index < length; index += 1) {
2358
+ tag = keys[index];
2359
+ style = String(map2[tag]);
2360
+ if (tag.slice(0, 2) === "!!") {
2361
+ tag = "tag:yaml.org,2002:" + tag.slice(2);
2362
+ }
2363
+ type2 = schema2.compiledTypeMap["fallback"][tag];
2364
+ if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
2365
+ style = type2.styleAliases[style];
2513
2366
  }
2367
+ result[tag] = style;
2514
2368
  }
2515
- return false;
2369
+ return result;
2516
2370
  }
2517
- function writeNode(state, level, object, block, compact, iskey, isblockseq) {
2518
- state.tag = null;
2519
- state.dump = object;
2520
- if (!detectType(state, object, false)) {
2521
- detectType(state, object, true);
2522
- }
2523
- var type2 = _toString.call(state.dump);
2524
- var inblock = block;
2525
- var tagStr;
2526
- if (block) {
2527
- block = state.flowLevel < 0 || state.flowLevel > level;
2528
- }
2529
- var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate;
2530
- if (objectOrArray) {
2531
- duplicateIndex = state.duplicates.indexOf(object);
2532
- duplicate = duplicateIndex !== -1;
2533
- }
2534
- if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
2535
- compact = false;
2536
- }
2537
- if (duplicate && state.usedDuplicates[duplicateIndex]) {
2538
- state.dump = "*ref_" + duplicateIndex;
2371
+ function encodeHex(character) {
2372
+ var string, handle, length;
2373
+ string = character.toString(16).toUpperCase();
2374
+ if (character <= 255) {
2375
+ handle = "x";
2376
+ length = 2;
2377
+ } else if (character <= 65535) {
2378
+ handle = "u";
2379
+ length = 4;
2380
+ } else if (character <= 4294967295) {
2381
+ handle = "U";
2382
+ length = 8;
2539
2383
  } else {
2540
- if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
2541
- state.usedDuplicates[duplicateIndex] = true;
2542
- }
2543
- if (type2 === "[object Object]") {
2544
- if (block && Object.keys(state.dump).length !== 0) {
2545
- writeBlockMapping(state, level, state.dump, compact);
2546
- if (duplicate) {
2547
- state.dump = "&ref_" + duplicateIndex + state.dump;
2548
- }
2549
- } else {
2550
- writeFlowMapping(state, level, state.dump);
2551
- if (duplicate) {
2552
- state.dump = "&ref_" + duplicateIndex + " " + state.dump;
2553
- }
2554
- }
2555
- } else if (type2 === "[object Array]") {
2556
- if (block && state.dump.length !== 0) {
2557
- if (state.noArrayIndent && !isblockseq && level > 0) {
2558
- writeBlockSequence(state, level - 1, state.dump, compact);
2559
- } else {
2560
- writeBlockSequence(state, level, state.dump, compact);
2561
- }
2562
- if (duplicate) {
2563
- state.dump = "&ref_" + duplicateIndex + state.dump;
2564
- }
2565
- } else {
2566
- writeFlowSequence(state, level, state.dump);
2567
- if (duplicate) {
2568
- state.dump = "&ref_" + duplicateIndex + " " + state.dump;
2569
- }
2570
- }
2571
- } else if (type2 === "[object String]") {
2572
- if (state.tag !== "?") {
2573
- writeScalar(state, state.dump, level, iskey, inblock);
2574
- }
2575
- } else if (type2 === "[object Undefined]") {
2576
- return false;
2577
- } else {
2578
- if (state.skipInvalid)
2579
- return false;
2580
- throw new exception("unacceptable kind of an object to dump " + type2);
2581
- }
2582
- if (state.tag !== null && state.tag !== "?") {
2583
- tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21");
2584
- if (state.tag[0] === "!") {
2585
- tagStr = "!" + tagStr;
2586
- } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
2587
- tagStr = "!!" + tagStr.slice(18);
2588
- } else {
2589
- tagStr = "!<" + tagStr + ">";
2590
- }
2591
- state.dump = tagStr + " " + state.dump;
2592
- }
2384
+ throw new exception("code point within a string may not be greater than 0xFFFFFFFF");
2593
2385
  }
2594
- return true;
2386
+ return "\\" + handle + common.repeat("0", length - string.length) + string;
2595
2387
  }
2596
- function getDuplicateReferences(object, state) {
2597
- var objects = [], duplicatesIndexes = [], index, length;
2598
- inspectNode(object, objects, duplicatesIndexes);
2599
- for (index = 0, length = duplicatesIndexes.length;index < length; index += 1) {
2600
- state.duplicates.push(objects[duplicatesIndexes[index]]);
2601
- }
2602
- state.usedDuplicates = new Array(length);
2388
+ var QUOTING_TYPE_SINGLE = 1;
2389
+ var QUOTING_TYPE_DOUBLE = 2;
2390
+ function State(options) {
2391
+ this.schema = options["schema"] || _default;
2392
+ this.indent = Math.max(1, options["indent"] || 2);
2393
+ this.noArrayIndent = options["noArrayIndent"] || false;
2394
+ this.skipInvalid = options["skipInvalid"] || false;
2395
+ this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
2396
+ this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
2397
+ this.sortKeys = options["sortKeys"] || false;
2398
+ this.lineWidth = options["lineWidth"] || 80;
2399
+ this.noRefs = options["noRefs"] || false;
2400
+ this.noCompatMode = options["noCompatMode"] || false;
2401
+ this.condenseFlow = options["condenseFlow"] || false;
2402
+ this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
2403
+ this.forceQuotes = options["forceQuotes"] || false;
2404
+ this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
2405
+ this.implicitTypes = this.schema.compiledImplicit;
2406
+ this.explicitTypes = this.schema.compiledExplicit;
2407
+ this.tag = null;
2408
+ this.result = "";
2409
+ this.duplicates = [];
2410
+ this.usedDuplicates = null;
2603
2411
  }
2604
- function inspectNode(object, objects, duplicatesIndexes) {
2605
- var objectKeyList, index, length;
2606
- if (object !== null && typeof object === "object") {
2607
- index = objects.indexOf(object);
2608
- if (index !== -1) {
2609
- if (duplicatesIndexes.indexOf(index) === -1) {
2610
- duplicatesIndexes.push(index);
2611
- }
2412
+ function indentString(string, spaces) {
2413
+ var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string.length;
2414
+ while (position < length) {
2415
+ next = string.indexOf(`
2416
+ `, position);
2417
+ if (next === -1) {
2418
+ line = string.slice(position);
2419
+ position = length;
2612
2420
  } else {
2613
- objects.push(object);
2614
- if (Array.isArray(object)) {
2615
- for (index = 0, length = object.length;index < length; index += 1) {
2616
- inspectNode(object[index], objects, duplicatesIndexes);
2617
- }
2618
- } else {
2619
- objectKeyList = Object.keys(object);
2620
- for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2621
- inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
2622
- }
2623
- }
2421
+ line = string.slice(position, next + 1);
2422
+ position = next + 1;
2624
2423
  }
2424
+ if (line.length && line !== `
2425
+ `)
2426
+ result += ind;
2427
+ result += line;
2625
2428
  }
2429
+ return result;
2626
2430
  }
2627
- function dump$1(input, options) {
2628
- options = options || {};
2629
- var state = new State(options);
2630
- if (!state.noRefs)
2631
- getDuplicateReferences(input, state);
2632
- var value = input;
2633
- if (state.replacer) {
2634
- value = state.replacer.call({ "": value }, "", value);
2431
+ function generateNextLine(state, level) {
2432
+ return `
2433
+ ` + common.repeat(" ", state.indent * level);
2434
+ }
2435
+ function testImplicitResolving(state, str2) {
2436
+ var index, length, type2;
2437
+ for (index = 0, length = state.implicitTypes.length;index < length; index += 1) {
2438
+ type2 = state.implicitTypes[index];
2439
+ if (type2.resolve(str2)) {
2440
+ return true;
2441
+ }
2635
2442
  }
2636
- if (writeNode(state, 0, value, true, true))
2637
- return state.dump + `
2638
- `;
2639
- return "";
2443
+ return false;
2640
2444
  }
2641
- var dump_1 = dump$1;
2642
- var dumper = {
2643
- dump: dump_1
2644
- };
2645
- function renamed(from, to) {
2646
- return function() {
2647
- throw new Error("Function yaml." + from + " is removed in js-yaml 4. " + "Use yaml." + to + " instead, which is now safe by default.");
2648
- };
2445
+ function isWhitespace(c) {
2446
+ return c === CHAR_SPACE || c === CHAR_TAB;
2649
2447
  }
2650
- var Type = type;
2651
- var Schema = schema;
2652
- var FAILSAFE_SCHEMA = failsafe;
2653
- var JSON_SCHEMA = json;
2654
- var CORE_SCHEMA = core;
2655
- var DEFAULT_SCHEMA = _default;
2656
- var load = loader.load;
2657
- var loadAll = loader.loadAll;
2658
- var dump = dumper.dump;
2659
- var YAMLException = exception;
2660
- var types = {
2661
- binary,
2662
- float,
2663
- map,
2664
- null: _null,
2665
- pairs,
2666
- set,
2667
- timestamp,
2668
- bool,
2669
- int,
2670
- merge,
2671
- omap,
2672
- seq,
2673
- str
2674
- };
2675
- var safeLoad = renamed("safeLoad", "load");
2676
- var safeLoadAll = renamed("safeLoadAll", "loadAll");
2677
- var safeDump = renamed("safeDump", "dump");
2678
- var jsYaml = {
2679
- Type,
2680
- Schema,
2681
- FAILSAFE_SCHEMA,
2682
- JSON_SCHEMA,
2683
- CORE_SCHEMA,
2684
- DEFAULT_SCHEMA,
2685
- load,
2686
- loadAll,
2687
- dump,
2688
- YAMLException,
2689
- types,
2690
- safeLoad,
2691
- safeLoadAll,
2692
- safeDump
2693
- };
2694
-
2695
- // src/tui.ts
2696
- var MANIFOLD_AGENTS = ["clerk", "senior-dev", "junior-dev", "debug"];
2697
- async function getManifoldAgents(directory) {
2698
- const agentsDir = join(directory, ".opencode", "agents");
2699
- if (!existsSync(agentsDir)) {
2700
- return [];
2448
+ function isPrintable(c) {
2449
+ return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;
2450
+ }
2451
+ function isNsCharOrWhitespace(c) {
2452
+ return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
2453
+ }
2454
+ function isPlainSafe(c, prev, inblock) {
2455
+ var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
2456
+ var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
2457
+ return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar;
2458
+ }
2459
+ function isPlainSafeFirst(c) {
2460
+ return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
2461
+ }
2462
+ function isPlainSafeLast(c) {
2463
+ return !isWhitespace(c) && c !== CHAR_COLON;
2464
+ }
2465
+ function codePointAt(string, pos) {
2466
+ var first = string.charCodeAt(pos), second;
2467
+ if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
2468
+ second = string.charCodeAt(pos + 1);
2469
+ if (second >= 56320 && second <= 57343) {
2470
+ return (first - 55296) * 1024 + second - 56320 + 65536;
2471
+ }
2701
2472
  }
2702
- const files = await readdir(agentsDir);
2703
- const agents = [];
2704
- for (const file of files) {
2705
- if (!file.endsWith(".md"))
2706
- continue;
2707
- const name = file.replace(".md", "");
2708
- if (MANIFOLD_AGENTS.includes(name)) {
2709
- agents.push(name);
2710
- }
2711
- }
2712
- return agents;
2713
- }
2714
- async function readAgentFile(agentName, directory) {
2715
- const agentPath = join(directory, ".opencode", "agents", `${agentName}.md`);
2716
- if (!existsSync(agentPath)) {
2717
- const globalPath = join(homedir(), ".config", "opencode", "manifold", "agents", `${agentName}.md`);
2718
- if (existsSync(globalPath)) {
2719
- const content2 = await readFile(globalPath, "utf-8");
2720
- const { frontmatter: frontmatter2, body: body2 } = parseFrontmatter(content2);
2721
- return { content: content2, frontmatter: frontmatter2, body: body2 };
2722
- }
2723
- throw new Error(`Agent file not found for ${agentName}`);
2724
- }
2725
- const content = await readFile(agentPath, "utf-8");
2726
- const { frontmatter, body } = parseFrontmatter(content);
2727
- return { content, frontmatter, body };
2728
- }
2729
- function parseFrontmatter(content) {
2730
- const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
2731
- if (!match) {
2732
- return { frontmatter: {}, body: content };
2733
- }
2734
- const frontmatterYaml = match[1];
2735
- const body = match[2];
2736
- const frontmatter = jsYaml.load(frontmatterYaml) || {};
2737
- return { frontmatter, body };
2738
- }
2739
- function buildAgentFile(frontmatter, body) {
2740
- const yamlContent = jsYaml.dump(frontmatter, {
2741
- lineWidth: -1,
2742
- noCompatMode: true
2743
- });
2744
- return `---
2745
- ${yamlContent}---
2746
- ${body}`;
2747
- }
2748
- async function updateAgentModel(agentName, modelId, directory) {
2749
- const { frontmatter, body } = await readAgentFile(agentName, directory);
2750
- frontmatter.model = modelId;
2751
- const newContent = buildAgentFile(frontmatter, body);
2752
- const agentPath = join(directory, ".opencode", "agents", `${agentName}.md`);
2753
- await writeFile(agentPath, newContent);
2754
- }
2755
- var tui = async (api) => {
2756
- api.command.register(() => [
2757
- {
2758
- title: "Manifold Models",
2759
- value: "manifold-models",
2760
- description: "Set the model for a Manifold sub-agent",
2761
- category: "Manifold",
2762
- slash: {
2763
- name: "manifold-models"
2764
- }
2765
- },
2766
- {
2767
- title: "Manifold Update",
2768
- value: "manifold-update",
2769
- description: "Clear opencode-manifold plugin cache and prompt for restart",
2770
- category: "Manifold",
2771
- slash: {
2772
- name: "manifold-update"
2473
+ return first;
2474
+ }
2475
+ function needIndentIndicator(string) {
2476
+ var leadingSpaceRe = /^\n* /;
2477
+ return leadingSpaceRe.test(string);
2478
+ }
2479
+ var STYLE_PLAIN = 1;
2480
+ var STYLE_SINGLE = 2;
2481
+ var STYLE_LITERAL = 3;
2482
+ var STYLE_FOLDED = 4;
2483
+ var STYLE_DOUBLE = 5;
2484
+ function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
2485
+ var i2;
2486
+ var char = 0;
2487
+ var prevChar = null;
2488
+ var hasLineBreak = false;
2489
+ var hasFoldableLine = false;
2490
+ var shouldTrackWidth = lineWidth !== -1;
2491
+ var previousLineBreak = -1;
2492
+ var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
2493
+ if (singleLineOnly || forceQuotes) {
2494
+ for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2495
+ char = codePointAt(string, i2);
2496
+ if (!isPrintable(char)) {
2497
+ return STYLE_DOUBLE;
2773
2498
  }
2499
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2500
+ prevChar = char;
2774
2501
  }
2775
- ]);
2776
- api.event.on("tui.command.execute", async (event) => {
2777
- if (event.properties.command === "manifold-models") {
2778
- await handleManifoldModels(api);
2779
- } else if (event.properties.command === "manifold-update") {
2780
- await handleManifoldUpdate(api);
2502
+ } else {
2503
+ for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2504
+ char = codePointAt(string, i2);
2505
+ if (char === CHAR_LINE_FEED) {
2506
+ hasLineBreak = true;
2507
+ if (shouldTrackWidth) {
2508
+ hasFoldableLine = hasFoldableLine || i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
2509
+ previousLineBreak = i2;
2510
+ }
2511
+ } else if (!isPrintable(char)) {
2512
+ return STYLE_DOUBLE;
2513
+ }
2514
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2515
+ prevChar = char;
2781
2516
  }
2782
- });
2783
- };
2784
- async function handleManifoldModels(api) {
2785
- const directory = api.state.path.directory;
2786
- const agents = await getManifoldAgents(directory);
2787
- if (agents.length === 0) {
2788
- api.ui.toast({
2789
- variant: "error",
2790
- message: "No Manifold agents found. Run /manifold-init first."
2791
- });
2792
- return;
2517
+ hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
2793
2518
  }
2794
- const providers = api.state.provider;
2795
- const models = [];
2796
- for (const provider of providers) {
2797
- if (provider.models) {
2798
- for (const [modelId, model] of Object.entries(provider.models)) {
2799
- models.push({
2800
- id: `${provider.id}/${modelId}`,
2801
- name: model.name || modelId,
2802
- providerID: provider.id
2803
- });
2804
- }
2519
+ if (!hasLineBreak && !hasFoldableLine) {
2520
+ if (plain && !forceQuotes && !testAmbiguousType(string)) {
2521
+ return STYLE_PLAIN;
2805
2522
  }
2523
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2806
2524
  }
2807
- if (models.length === 0) {
2808
- api.ui.toast({
2809
- variant: "error",
2810
- message: "No models available. Configure providers first."
2811
- });
2812
- return;
2525
+ if (indentPerLevel > 9 && needIndentIndicator(string)) {
2526
+ return STYLE_DOUBLE;
2813
2527
  }
2814
- models.sort((a, b) => a.name.localeCompare(b.name));
2815
- const agentOptions = agents.map((agent) => ({
2816
- title: `${agent} (sub-agent)`,
2817
- value: agent,
2818
- description: `Configure model for ${agent}`
2819
- }));
2820
- api.ui.dialog.setSize("medium");
2821
- return new Promise((resolve) => {
2822
- api.ui.ui.DialogSelect({
2823
- title: "Select Manifold Sub-Agent",
2824
- options: agentOptions,
2825
- onSelect: async (option) => {
2826
- const selectedAgent = option.value;
2827
- const currentModel = await readAgentFile(selectedAgent, directory).then((f) => f.frontmatter.model || "not set").catch(() => "not set");
2828
- const modelOptions = models.map((model) => ({
2829
- title: `${model.name}`,
2830
- value: model.id,
2831
- description: model.id,
2832
- footer: model.id === currentModel ? "✓ Current" : undefined
2833
- }));
2834
- api.ui.ui.DialogSelect({
2835
- title: `Select Model for ${selectedAgent}`,
2836
- options: modelOptions,
2837
- current: currentModel !== "not set" ? currentModel : undefined,
2838
- onSelect: async (modelOption) => {
2839
- const selectedModelId = modelOption.value;
2840
- await updateAgentModel(selectedAgent, selectedModelId, directory);
2841
- api.ui.toast({
2842
- variant: "success",
2843
- message: `Set ${selectedAgent} to ${selectedModelId}`
2844
- });
2845
- resolve();
2846
- }
2847
- });
2848
- }
2849
- });
2850
- });
2851
- }
2852
- async function handleManifoldUpdate(api) {
2853
- const directory = api.state.path.directory;
2854
- const settingsPath = join(directory, "Manifold", "settings.json");
2855
- let settings = {};
2856
- if (existsSync(settingsPath)) {
2857
- const content = await readFile(settingsPath, "utf-8");
2858
- try {
2859
- settings = JSON.parse(content);
2860
- } catch {}
2528
+ if (!forceQuotes) {
2529
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
2861
2530
  }
2862
- const configuredPaths = settings.updateCachePaths || [];
2863
- if (configuredPaths.length === 0) {
2864
- api.ui.dialog.setSize("large");
2865
- api.ui.ui.DialogSelect({
2866
- title: "Manifold Plugin Update",
2867
- options: [
2868
- {
2869
- title: "Configure Cache Paths",
2870
- value: "configure",
2871
- description: "Add updateCachePaths to Manifold/settings.json",
2872
- footer: "Opens settings file"
2873
- }
2874
- ],
2875
- onSelect: () => {
2876
- api.ui.toast({
2877
- variant: "info",
2878
- message: "Add updateCachePaths to Manifold/settings.json"
2879
- });
2531
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2532
+ }
2533
+ function writeScalar(state, string, level, iskey, inblock) {
2534
+ state.dump = function() {
2535
+ if (string.length === 0) {
2536
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
2537
+ }
2538
+ if (!state.noCompatMode) {
2539
+ if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
2540
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
2880
2541
  }
2881
- });
2882
- return;
2883
- }
2884
- const resolvedPaths = configuredPaths.map((p) => {
2885
- const expanded = p.startsWith("~") ? join(homedir(), p.slice(1)) : p;
2886
- return expanded;
2887
- });
2888
- api.ui.dialog.setSize("large");
2889
- return new Promise((resolve) => {
2890
- api.ui.ui.DialogSelect({
2891
- title: "Manifold Plugin Update",
2892
- options: [
2893
- {
2894
- title: "Clear Cache",
2895
- value: "confirm",
2896
- description: `Will clear ${resolvedPaths.length} path(s)`,
2897
- footer: resolvedPaths.map((p) => `• ${p}`).join(`
2898
- `)
2899
- },
2900
- {
2901
- title: "Cancel",
2902
- value: "cancel",
2903
- description: "Do not clear cache"
2904
- }
2905
- ],
2906
- onSelect: async (option) => {
2907
- if (option.value === "cancel") {
2908
- resolve();
2909
- return;
2910
- }
2911
- const { exec } = await import("child_process");
2912
- const { promisify } = await import("util");
2913
- const execAsync = promisify(exec);
2914
- const cleared = [];
2915
- const skipped = [];
2916
- const blocked = [];
2917
- for (const pathStr of resolvedPaths) {
2918
- try {
2919
- await execAsync(`rm -rf "${pathStr}"`);
2920
- cleared.push(pathStr);
2921
- } catch (error) {
2922
- blocked.push({ path: pathStr, reason: `Failed to delete: ${error}` });
2923
- }
2924
- }
2925
- let message = "";
2926
- if (cleared.length > 0) {
2927
- message += `✅ Cleared: ${cleared.length} path(s)
2542
+ }
2543
+ var indent = state.indent * Math.max(1, level);
2544
+ var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
2545
+ var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
2546
+ function testAmbiguity(string2) {
2547
+ return testImplicitResolving(state, string2);
2548
+ }
2549
+ switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
2550
+ case STYLE_PLAIN:
2551
+ return string;
2552
+ case STYLE_SINGLE:
2553
+ return "'" + string.replace(/'/g, "''") + "'";
2554
+ case STYLE_LITERAL:
2555
+ return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
2556
+ case STYLE_FOLDED:
2557
+ return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
2558
+ case STYLE_DOUBLE:
2559
+ return '"' + escapeString(string) + '"';
2560
+ default:
2561
+ throw new exception("impossible error: invalid scalar style");
2562
+ }
2563
+ }();
2564
+ }
2565
+ function blockHeader(string, indentPerLevel) {
2566
+ var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
2567
+ var clip = string[string.length - 1] === `
2928
2568
  `;
2929
- }
2930
- if (blocked.length > 0) {
2931
- message += `\uD83D\uDEAB Blocked: ${blocked.length} path(s)
2569
+ var keep = clip && (string[string.length - 2] === `
2570
+ ` || string === `
2571
+ `);
2572
+ var chomp = keep ? "+" : clip ? "" : "-";
2573
+ return indentIndicator + chomp + `
2932
2574
  `;
2933
- }
2934
- if (cleared.length > 0) {
2935
- message += `
2936
- Restart opencode to pull the latest plugin version.`;
2937
- }
2938
- api.ui.toast({
2939
- variant: cleared.length > 0 ? "success" : "error",
2940
- message: cleared.length > 0 ? `Cache cleared. Restart opencode to update.` : `Cache update blocked`
2941
- });
2942
- resolve();
2943
- }
2944
- });
2945
- });
2946
2575
  }
2947
-
2948
- // src/init.ts
2949
- import { readFile as readFile2, writeFile as writeFile2, mkdir, readdir as readdir2 } from "fs/promises";
2950
- import { existsSync as existsSync2 } from "fs";
2951
- import { join as join2, dirname } from "path";
2952
- import { fileURLToPath } from "url";
2953
- import { homedir as homedir2 } from "os";
2954
- import { createRequire as createRequire2 } from "module";
2955
- var __dirname2 = dirname(fileURLToPath(import.meta.url));
2956
- var require2 = createRequire2(import.meta.url);
2957
- var bundledTemplatesDir = join2(__dirname2, "..", "src", "templates");
2958
- var globalTemplatesDir = join2(homedir2(), ".config", "opencode", "manifold");
2959
- async function getPluginVersion() {
2960
- try {
2961
- const packageJson = require2(join2(__dirname2, "..", "package.json"));
2962
- return packageJson.version || "unknown";
2963
- } catch {
2964
- return "unknown";
2576
+ function dropEndingNewline(string) {
2577
+ return string[string.length - 1] === `
2578
+ ` ? string.slice(0, -1) : string;
2579
+ }
2580
+ function foldString(string, width) {
2581
+ var lineRe = /(\n+)([^\n]*)/g;
2582
+ var result = function() {
2583
+ var nextLF = string.indexOf(`
2584
+ `);
2585
+ nextLF = nextLF !== -1 ? nextLF : string.length;
2586
+ lineRe.lastIndex = nextLF;
2587
+ return foldLine(string.slice(0, nextLF), width);
2588
+ }();
2589
+ var prevMoreIndented = string[0] === `
2590
+ ` || string[0] === " ";
2591
+ var moreIndented;
2592
+ var match;
2593
+ while (match = lineRe.exec(string)) {
2594
+ var prefix = match[1], line = match[2];
2595
+ moreIndented = line[0] === " ";
2596
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? `
2597
+ ` : "") + foldLine(line, width);
2598
+ prevMoreIndented = moreIndented;
2965
2599
  }
2600
+ return result;
2966
2601
  }
2967
- async function dirHasContent(dirPath) {
2968
- if (!existsSync2(dirPath))
2969
- return false;
2970
- try {
2971
- const entries = await readdir2(dirPath);
2972
- return entries.length > 0;
2973
- } catch {
2974
- return false;
2602
+ function foldLine(line, width) {
2603
+ if (line === "" || line[0] === " ")
2604
+ return line;
2605
+ var breakRe = / [^ ]/g;
2606
+ var match;
2607
+ var start = 0, end, curr = 0, next = 0;
2608
+ var result = "";
2609
+ while (match = breakRe.exec(line)) {
2610
+ next = match.index;
2611
+ if (next - start > width) {
2612
+ end = curr > start ? curr : next;
2613
+ result += `
2614
+ ` + line.slice(start, end);
2615
+ start = end + 1;
2616
+ }
2617
+ curr = next;
2618
+ }
2619
+ result += `
2620
+ `;
2621
+ if (line.length - start > width && curr > start) {
2622
+ result += line.slice(start, curr) + `
2623
+ ` + line.slice(curr + 1);
2624
+ } else {
2625
+ result += line.slice(start);
2975
2626
  }
2627
+ return result.slice(1);
2976
2628
  }
2977
- async function copyFiles(src, dest) {
2978
- if (!existsSync2(src))
2979
- return [];
2980
- await mkdir(dest, { recursive: true });
2981
- const copied = [];
2982
- const entries = await readdir2(src, { withFileTypes: true });
2983
- for (const entry of entries) {
2984
- const srcPath = join2(src, entry.name);
2985
- const destPath = join2(dest, entry.name);
2986
- if (entry.isDirectory()) {
2987
- const subCopied = await copyFiles(srcPath, destPath);
2988
- if (subCopied.length > 0) {
2989
- copied.push(entry.name);
2990
- }
2629
+ function escapeString(string) {
2630
+ var result = "";
2631
+ var char = 0;
2632
+ var escapeSeq;
2633
+ for (var i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2634
+ char = codePointAt(string, i2);
2635
+ escapeSeq = ESCAPE_SEQUENCES[char];
2636
+ if (!escapeSeq && isPrintable(char)) {
2637
+ result += string[i2];
2638
+ if (char >= 65536)
2639
+ result += string[i2 + 1];
2991
2640
  } else {
2992
- await writeFile2(destPath, await readFile2(srcPath));
2993
- copied.push(entry.name);
2641
+ result += escapeSeq || encodeHex(char);
2642
+ }
2643
+ }
2644
+ return result;
2645
+ }
2646
+ function writeFlowSequence(state, level, object) {
2647
+ var _result = "", _tag = state.tag, index, length, value;
2648
+ for (index = 0, length = object.length;index < length; index += 1) {
2649
+ value = object[index];
2650
+ if (state.replacer) {
2651
+ value = state.replacer.call(object, String(index), value);
2652
+ }
2653
+ if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
2654
+ if (_result !== "")
2655
+ _result += "," + (!state.condenseFlow ? " " : "");
2656
+ _result += state.dump;
2994
2657
  }
2995
2658
  }
2996
- return copied;
2659
+ state.tag = _tag;
2660
+ state.dump = "[" + _result + "]";
2997
2661
  }
2998
- async function ensureGlobalTemplates(ctx) {
2999
- await ctx.client.app.log({
3000
- body: {
3001
- service: "opencode-manifold",
3002
- level: "info",
3003
- message: "Synchronizing global templates..."
2662
+ function writeBlockSequence(state, level, object, compact) {
2663
+ var _result = "", _tag = state.tag, index, length, value;
2664
+ for (index = 0, length = object.length;index < length; index += 1) {
2665
+ value = object[index];
2666
+ if (state.replacer) {
2667
+ value = state.replacer.call(object, String(index), value);
3004
2668
  }
3005
- });
3006
- if (!existsSync2(bundledTemplatesDir)) {
3007
- await ctx.client.app.log({
3008
- body: {
3009
- service: "opencode-manifold",
3010
- level: "error",
3011
- message: `Bundled templates not found at ${bundledTemplatesDir}`
2669
+ if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
2670
+ if (!compact || _result !== "") {
2671
+ _result += generateNextLine(state, level);
3012
2672
  }
3013
- });
3014
- return;
3015
- }
3016
- await copyFiles(bundledTemplatesDir, globalTemplatesDir);
3017
- const globalCommandsDir = join2(homedir2(), ".config", "opencode", "commands");
3018
- const bundledCommandsDir = join2(bundledTemplatesDir, "commands");
3019
- if (existsSync2(bundledCommandsDir)) {
3020
- await copyFiles(bundledCommandsDir, globalCommandsDir);
3021
- }
3022
- await ctx.client.app.log({
3023
- body: {
3024
- service: "opencode-manifold",
3025
- level: "info",
3026
- message: "Global templates synchronized"
2673
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2674
+ _result += "-";
2675
+ } else {
2676
+ _result += "- ";
2677
+ }
2678
+ _result += state.dump;
3027
2679
  }
3028
- });
2680
+ }
2681
+ state.tag = _tag;
2682
+ state.dump = _result || "[]";
3029
2683
  }
3030
- async function initProject(directory, client) {
3031
- const initialized = [];
3032
- await client.app.log({
3033
- body: {
3034
- service: "opencode-manifold",
3035
- level: "info",
3036
- message: `Running /manifold-init in ${directory}`
2684
+ function writeFlowMapping(state, level, object) {
2685
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;
2686
+ for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2687
+ pairBuffer = "";
2688
+ if (_result !== "")
2689
+ pairBuffer += ", ";
2690
+ if (state.condenseFlow)
2691
+ pairBuffer += '"';
2692
+ objectKey = objectKeyList[index];
2693
+ objectValue = object[objectKey];
2694
+ if (state.replacer) {
2695
+ objectValue = state.replacer.call(object, objectKey, objectValue);
3037
2696
  }
3038
- });
3039
- if (!await dirHasContent(globalTemplatesDir)) {
3040
- await client.app.log({
3041
- body: {
3042
- service: "opencode-manifold",
3043
- level: "error",
3044
- message: `Global templates not found at ${globalTemplatesDir}. Plugin may not have loaded correctly.`
3045
- }
3046
- });
3047
- return initialized;
3048
- }
3049
- const agentsCopied = await copyMissingFiles(join2(globalTemplatesDir, "agents"), join2(directory, ".opencode", "agents"));
3050
- if (agentsCopied.length > 0) {
3051
- initialized.push(`agents (${agentsCopied.join(", ")})`);
3052
- }
3053
- const skillsCopied = await copyMissingFiles(join2(globalTemplatesDir, "skills"), join2(directory, ".opencode", "skills"));
3054
- if (skillsCopied.length > 0) {
3055
- initialized.push(`skills (${skillsCopied.join(", ")})`);
2697
+ if (!writeNode(state, level, objectKey, false, false)) {
2698
+ continue;
2699
+ }
2700
+ if (state.dump.length > 1024)
2701
+ pairBuffer += "? ";
2702
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
2703
+ if (!writeNode(state, level, objectValue, false, false)) {
2704
+ continue;
2705
+ }
2706
+ pairBuffer += state.dump;
2707
+ _result += pairBuffer;
3056
2708
  }
3057
- const manifoldCopied = await copyMissingFiles(join2(globalTemplatesDir, "manifold"), join2(directory, "Manifold"));
3058
- if (manifoldCopied.length > 0) {
3059
- initialized.push(`Manifold/ (${manifoldCopied.join(", ")})`);
2709
+ state.tag = _tag;
2710
+ state.dump = "{" + _result + "}";
2711
+ }
2712
+ function writeBlockMapping(state, level, object, compact) {
2713
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;
2714
+ if (state.sortKeys === true) {
2715
+ objectKeyList.sort();
2716
+ } else if (typeof state.sortKeys === "function") {
2717
+ objectKeyList.sort(state.sortKeys);
2718
+ } else if (state.sortKeys) {
2719
+ throw new exception("sortKeys must be a boolean or a function");
3060
2720
  }
3061
- const version = await getPluginVersion();
3062
- await writeFile2(join2(directory, "Manifold", "VERSION"), version + `
3063
- `);
3064
- await client.app.log({
3065
- body: {
3066
- service: "opencode-manifold",
3067
- level: "info",
3068
- message: `/manifold-init complete: ${initialized.join(", ") || "already initialized"}`
2721
+ for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2722
+ pairBuffer = "";
2723
+ if (!compact || _result !== "") {
2724
+ pairBuffer += generateNextLine(state, level);
3069
2725
  }
3070
- });
3071
- return initialized;
2726
+ objectKey = objectKeyList[index];
2727
+ objectValue = object[objectKey];
2728
+ if (state.replacer) {
2729
+ objectValue = state.replacer.call(object, objectKey, objectValue);
2730
+ }
2731
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
2732
+ continue;
2733
+ }
2734
+ explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
2735
+ if (explicitPair) {
2736
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2737
+ pairBuffer += "?";
2738
+ } else {
2739
+ pairBuffer += "? ";
2740
+ }
2741
+ }
2742
+ pairBuffer += state.dump;
2743
+ if (explicitPair) {
2744
+ pairBuffer += generateNextLine(state, level);
2745
+ }
2746
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
2747
+ continue;
2748
+ }
2749
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2750
+ pairBuffer += ":";
2751
+ } else {
2752
+ pairBuffer += ": ";
2753
+ }
2754
+ pairBuffer += state.dump;
2755
+ _result += pairBuffer;
2756
+ }
2757
+ state.tag = _tag;
2758
+ state.dump = _result || "{}";
3072
2759
  }
3073
-
3074
- // src/tools/dispatch-task.ts
3075
- import { tool } from "@opencode-ai/plugin";
3076
- import { readFile as readFile5, writeFile as writeFile5 } from "fs/promises";
3077
- import { existsSync as existsSync6 } from "fs";
3078
- import { join as join6 } from "path";
3079
-
3080
- // src/state-machine.ts
3081
- import { readFile as readFile4, writeFile as writeFile4, readdir as readdir3 } from "fs/promises";
3082
- import { existsSync as existsSync5 } from "fs";
3083
- import { join as join5 } from "path";
3084
-
3085
- // src/session-spawner.ts
3086
- async function waitForSessionIdle(client, sessionId, timeoutMs) {
3087
- const startTime = Date.now();
3088
- while (Date.now() - startTime < timeoutMs) {
3089
- const statusResponse = await client.session.status({});
3090
- const statusData = statusResponse.data;
3091
- if (statusData && statusData[sessionId]) {
3092
- const status = statusData[sessionId];
3093
- if (status.type === "idle") {
3094
- return true;
2760
+ function detectType(state, object, explicit) {
2761
+ var _result, typeList, index, length, type2, style;
2762
+ typeList = explicit ? state.explicitTypes : state.implicitTypes;
2763
+ for (index = 0, length = typeList.length;index < length; index += 1) {
2764
+ type2 = typeList[index];
2765
+ if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
2766
+ if (explicit) {
2767
+ if (type2.multi && type2.representName) {
2768
+ state.tag = type2.representName(object);
2769
+ } else {
2770
+ state.tag = type2.tag;
2771
+ }
2772
+ } else {
2773
+ state.tag = "?";
3095
2774
  }
3096
- if (status.type === "retry") {
3097
- const waitTime = status.next - Date.now();
3098
- if (waitTime > 0) {
3099
- await new Promise((resolve) => setTimeout(resolve, Math.min(waitTime, 1000)));
2775
+ if (type2.represent) {
2776
+ style = state.styleMap[type2.tag] || type2.defaultStyle;
2777
+ if (_toString.call(type2.represent) === "[object Function]") {
2778
+ _result = type2.represent(object, style);
2779
+ } else if (_hasOwnProperty.call(type2.represent, style)) {
2780
+ _result = type2.represent[style](object, style);
2781
+ } else {
2782
+ throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
3100
2783
  }
3101
- continue;
2784
+ state.dump = _result;
3102
2785
  }
2786
+ return true;
3103
2787
  }
3104
- await new Promise((resolve) => setTimeout(resolve, 500));
3105
2788
  }
3106
2789
  return false;
3107
2790
  }
3108
- async function getLastAssistantMessage(client, sessionId) {
3109
- const messagesResponse = await client.session.messages({
3110
- path: { id: sessionId }
3111
- });
3112
- const messages = messagesResponse.data;
3113
- if (!messages || !Array.isArray(messages)) {
3114
- return "";
2791
+ function writeNode(state, level, object, block, compact, iskey, isblockseq) {
2792
+ state.tag = null;
2793
+ state.dump = object;
2794
+ if (!detectType(state, object, false)) {
2795
+ detectType(state, object, true);
3115
2796
  }
3116
- for (let i2 = messages.length - 1;i2 >= 0; i2--) {
3117
- const msg = messages[i2];
3118
- if (msg.info && msg.info.role === "assistant") {
3119
- if (msg.parts && Array.isArray(msg.parts)) {
3120
- for (const part of msg.parts) {
3121
- if (part.type === "text" && part.text) {
3122
- return part.text;
3123
- }
2797
+ var type2 = _toString.call(state.dump);
2798
+ var inblock = block;
2799
+ var tagStr;
2800
+ if (block) {
2801
+ block = state.flowLevel < 0 || state.flowLevel > level;
2802
+ }
2803
+ var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate;
2804
+ if (objectOrArray) {
2805
+ duplicateIndex = state.duplicates.indexOf(object);
2806
+ duplicate = duplicateIndex !== -1;
2807
+ }
2808
+ if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
2809
+ compact = false;
2810
+ }
2811
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
2812
+ state.dump = "*ref_" + duplicateIndex;
2813
+ } else {
2814
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
2815
+ state.usedDuplicates[duplicateIndex] = true;
2816
+ }
2817
+ if (type2 === "[object Object]") {
2818
+ if (block && Object.keys(state.dump).length !== 0) {
2819
+ writeBlockMapping(state, level, state.dump, compact);
2820
+ if (duplicate) {
2821
+ state.dump = "&ref_" + duplicateIndex + state.dump;
2822
+ }
2823
+ } else {
2824
+ writeFlowMapping(state, level, state.dump);
2825
+ if (duplicate) {
2826
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
2827
+ }
2828
+ }
2829
+ } else if (type2 === "[object Array]") {
2830
+ if (block && state.dump.length !== 0) {
2831
+ if (state.noArrayIndent && !isblockseq && level > 0) {
2832
+ writeBlockSequence(state, level - 1, state.dump, compact);
2833
+ } else {
2834
+ writeBlockSequence(state, level, state.dump, compact);
3124
2835
  }
2836
+ if (duplicate) {
2837
+ state.dump = "&ref_" + duplicateIndex + state.dump;
2838
+ }
2839
+ } else {
2840
+ writeFlowSequence(state, level, state.dump);
2841
+ if (duplicate) {
2842
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
2843
+ }
2844
+ }
2845
+ } else if (type2 === "[object String]") {
2846
+ if (state.tag !== "?") {
2847
+ writeScalar(state, state.dump, level, iskey, inblock);
2848
+ }
2849
+ } else if (type2 === "[object Undefined]") {
2850
+ return false;
2851
+ } else {
2852
+ if (state.skipInvalid)
2853
+ return false;
2854
+ throw new exception("unacceptable kind of an object to dump " + type2);
2855
+ }
2856
+ if (state.tag !== null && state.tag !== "?") {
2857
+ tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21");
2858
+ if (state.tag[0] === "!") {
2859
+ tagStr = "!" + tagStr;
2860
+ } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
2861
+ tagStr = "!!" + tagStr.slice(18);
2862
+ } else {
2863
+ tagStr = "!<" + tagStr + ">";
3125
2864
  }
2865
+ state.dump = tagStr + " " + state.dump;
3126
2866
  }
3127
2867
  }
3128
- return "";
2868
+ return true;
3129
2869
  }
3130
- async function cleanupSession(client, sessionId) {
3131
- try {
3132
- await client.session.delete({ path: { id: sessionId } });
3133
- } catch {}
2870
+ function getDuplicateReferences(object, state) {
2871
+ var objects = [], duplicatesIndexes = [], index, length;
2872
+ inspectNode(object, objects, duplicatesIndexes);
2873
+ for (index = 0, length = duplicatesIndexes.length;index < length; index += 1) {
2874
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
2875
+ }
2876
+ state.usedDuplicates = new Array(length);
3134
2877
  }
3135
- async function spawnSession(client, agent, prompt, timeoutSeconds) {
3136
- const timeoutMs = timeoutSeconds * 1000;
3137
- try {
3138
- const createResponse = await client.session.create({});
3139
- const session = createResponse.data;
3140
- if (!session || !session.id) {
3141
- return {
3142
- content: "",
3143
- success: false,
3144
- error: "Failed to create session"
3145
- };
3146
- }
3147
- const sessionId = session.id;
3148
- await client.app.log({
3149
- body: {
3150
- service: "opencode-manifold",
3151
- level: "info",
3152
- message: `Created session ${sessionId} for agent ${agent}`
2878
+ function inspectNode(object, objects, duplicatesIndexes) {
2879
+ var objectKeyList, index, length;
2880
+ if (object !== null && typeof object === "object") {
2881
+ index = objects.indexOf(object);
2882
+ if (index !== -1) {
2883
+ if (duplicatesIndexes.indexOf(index) === -1) {
2884
+ duplicatesIndexes.push(index);
3153
2885
  }
3154
- });
3155
- try {
3156
- await client.session.promptAsync({
3157
- path: { id: sessionId },
3158
- body: {
3159
- agent,
3160
- noReply: true,
3161
- parts: [{ type: "text", text: prompt }]
2886
+ } else {
2887
+ objects.push(object);
2888
+ if (Array.isArray(object)) {
2889
+ for (index = 0, length = object.length;index < length; index += 1) {
2890
+ inspectNode(object[index], objects, duplicatesIndexes);
3162
2891
  }
3163
- });
3164
- const isIdle = await waitForSessionIdle(client, sessionId, timeoutMs);
3165
- if (!isIdle) {
3166
- await client.session.abort({ path: { id: sessionId } });
3167
- return {
3168
- content: "",
3169
- success: false,
3170
- error: `Session timed out after ${timeoutSeconds}s`
3171
- };
3172
- }
3173
- const content = await getLastAssistantMessage(client, sessionId);
3174
- await client.app.log({
3175
- body: {
3176
- service: "opencode-manifold",
3177
- level: "info",
3178
- message: `Session ${sessionId} completed, content length: ${content.length}`
2892
+ } else {
2893
+ objectKeyList = Object.keys(object);
2894
+ for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2895
+ inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
3179
2896
  }
3180
- });
3181
- return {
3182
- content,
3183
- success: true
3184
- };
3185
- } finally {
3186
- await cleanupSession(client, sessionId);
3187
- }
3188
- } catch (error) {
3189
- return {
3190
- content: "",
3191
- success: false,
3192
- error: error instanceof Error ? error.message : String(error)
3193
- };
3194
- }
3195
- }
3196
- async function spawnClerkSession(client, prompt, agent, timeout) {
3197
- await client.app.log({
3198
- body: {
3199
- service: "opencode-manifold",
3200
- level: "info",
3201
- message: `Spawning Clerk session (agent: ${agent}, timeout: ${timeout}s)`
3202
- }
3203
- });
3204
- return spawnSession(client, agent, prompt, timeout);
3205
- }
3206
- async function spawnSeniorDevSession(client, prompt, agent, timeout) {
3207
- await client.app.log({
3208
- body: {
3209
- service: "opencode-manifold",
3210
- level: "info",
3211
- message: `Spawning Senior Dev session (agent: ${agent}, timeout: ${timeout}s)`
3212
- }
3213
- });
3214
- return spawnSession(client, agent, prompt, timeout);
3215
- }
3216
- async function spawnJuniorDevSession(client, prompt, seniorOutput, agent, timeout) {
3217
- await client.app.log({
3218
- body: {
3219
- service: "opencode-manifold",
3220
- level: "info",
3221
- message: `Spawning Junior Dev session (agent: ${agent}, timeout: ${timeout}s)`
3222
- }
3223
- });
3224
- const fullPrompt = `${prompt}
3225
-
3226
- ---
3227
-
3228
- Senior Dev's Implementation:
3229
- ${seniorOutput}`;
3230
- return spawnSession(client, agent, fullPrompt, timeout);
3231
- }
3232
- async function spawnDebugSession(client, prompt, loopHistory, agent, timeout) {
3233
- await client.app.log({
3234
- body: {
3235
- service: "opencode-manifold",
3236
- level: "info",
3237
- message: `Spawning Debug session (agent: ${agent}, timeout: ${timeout}s)`
2897
+ }
3238
2898
  }
3239
- });
3240
- const fullPrompt = `${prompt}
3241
-
3242
- ---
3243
-
3244
- Loop History:
3245
- ${loopHistory}`;
3246
- return spawnSession(client, agent, fullPrompt, timeout);
3247
- }
3248
- function parseJuniorFirstWord(response) {
3249
- const firstWord = response.trim().split(/\s+/)[0].toUpperCase();
3250
- if (firstWord === "COMPLETE") {
3251
- return "COMPLETE";
3252
2899
  }
3253
- return "QUESTIONS";
3254
2900
  }
3255
-
3256
- // src/error-handler.ts
3257
- class ModelCallError extends Error {
3258
- agent;
3259
- attempt;
3260
- constructor(message, agent, attempt) {
3261
- super(message);
3262
- this.agent = agent;
3263
- this.attempt = attempt;
3264
- this.name = "ModelCallError";
2901
+ function dump$1(input, options) {
2902
+ options = options || {};
2903
+ var state = new State(options);
2904
+ if (!state.noRefs)
2905
+ getDuplicateReferences(input, state);
2906
+ var value = input;
2907
+ if (state.replacer) {
2908
+ value = state.replacer.call({ "": value }, "", value);
3265
2909
  }
2910
+ if (writeNode(state, 0, value, true, true))
2911
+ return state.dump + `
2912
+ `;
2913
+ return "";
3266
2914
  }
3267
- async function retryWithBackoff(fn, options) {
3268
- let lastError;
3269
- for (let attempt = 0;attempt <= options.maxRetries; attempt++) {
3270
- try {
3271
- return await fn();
3272
- } catch (error) {
3273
- lastError = error instanceof Error ? error : new Error(String(error));
3274
- if (attempt < options.maxRetries) {
3275
- options.onRetry?.(attempt + 1, lastError);
3276
- const delay = Math.pow(2, attempt) * 100;
3277
- await new Promise((resolve) => setTimeout(resolve, delay));
3278
- }
3279
- }
3280
- }
3281
- throw lastError;
2915
+ var dump_1 = dump$1;
2916
+ var dumper = {
2917
+ dump: dump_1
2918
+ };
2919
+ function renamed(from, to) {
2920
+ return function() {
2921
+ throw new Error("Function yaml." + from + " is removed in js-yaml 4. " + "Use yaml." + to + " instead, which is now safe by default.");
2922
+ };
3282
2923
  }
2924
+ var Type = type;
2925
+ var Schema = schema;
2926
+ var FAILSAFE_SCHEMA = failsafe;
2927
+ var JSON_SCHEMA = json;
2928
+ var CORE_SCHEMA = core;
2929
+ var DEFAULT_SCHEMA = _default;
2930
+ var load = loader.load;
2931
+ var loadAll = loader.loadAll;
2932
+ var dump = dumper.dump;
2933
+ var YAMLException = exception;
2934
+ var types = {
2935
+ binary,
2936
+ float,
2937
+ map,
2938
+ null: _null,
2939
+ pairs,
2940
+ set,
2941
+ timestamp,
2942
+ bool,
2943
+ int,
2944
+ merge,
2945
+ omap,
2946
+ seq,
2947
+ str
2948
+ };
2949
+ var safeLoad = renamed("safeLoad", "load");
2950
+ var safeLoadAll = renamed("safeLoadAll", "loadAll");
2951
+ var safeDump = renamed("safeDump", "dump");
2952
+ var jsYaml = {
2953
+ Type,
2954
+ Schema,
2955
+ FAILSAFE_SCHEMA,
2956
+ JSON_SCHEMA,
2957
+ CORE_SCHEMA,
2958
+ DEFAULT_SCHEMA,
2959
+ load,
2960
+ loadAll,
2961
+ dump,
2962
+ YAMLException,
2963
+ types,
2964
+ safeLoad,
2965
+ safeLoadAll,
2966
+ safeDump
2967
+ };
3283
2968
 
3284
2969
  // src/graph.ts
3285
- import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir2 } from "fs/promises";
3286
- import { existsSync as existsSync3 } from "fs";
3287
- import { join as join3, dirname as dirname2 } from "path";
3288
2970
  var ENCODE_MAP = { "/": "__SL__", ".": "__DT__" };
3289
2971
  var ENCODE_RE = /[/.]/g;
3290
2972
  function pathToGraphFilename(filePath) {
@@ -3394,12 +3076,12 @@ ${tasksSection}
3394
3076
  }
3395
3077
  async function readGraphFile(directory, filePath) {
3396
3078
  const filename = pathToGraphFilename(filePath);
3397
- const graphPath = join3(directory, "Manifold", "graph", filename);
3398
- if (!existsSync3(graphPath)) {
3079
+ const graphPath = join2(directory, "Manifold", "graph", filename);
3080
+ if (!existsSync2(graphPath)) {
3399
3081
  return null;
3400
3082
  }
3401
3083
  try {
3402
- const content = await readFile3(graphPath, "utf-8");
3084
+ const content = await readFile2(graphPath, "utf-8");
3403
3085
  return parseGraphContent(content);
3404
3086
  } catch {
3405
3087
  return null;
@@ -3407,9 +3089,9 @@ async function readGraphFile(directory, filePath) {
3407
3089
  }
3408
3090
  async function updateGraphFile(directory, filePath, taskId, calls, dependsOn) {
3409
3091
  const filename = pathToGraphFilename(filePath);
3410
- const graphPath = join3(directory, "Manifold", "graph", filename);
3092
+ const graphPath = join2(directory, "Manifold", "graph", filename);
3411
3093
  let entry;
3412
- if (existsSync3(graphPath)) {
3094
+ if (existsSync2(graphPath)) {
3413
3095
  const existing = await readGraphFile(directory, filePath);
3414
3096
  entry = existing || {
3415
3097
  filePath,
@@ -3435,11 +3117,11 @@ async function updateGraphFile(directory, filePath, taskId, calls, dependsOn) {
3435
3117
  entry.tasksThatEdited.push(taskId);
3436
3118
  }
3437
3119
  const graphDir = dirname2(graphPath);
3438
- if (!existsSync3(graphDir)) {
3120
+ if (!existsSync2(graphDir)) {
3439
3121
  await mkdir2(graphDir, { recursive: true });
3440
3122
  }
3441
3123
  const content = formatGraphContent(entry);
3442
- await writeFile3(graphPath, content, "utf-8");
3124
+ await writeFile2(graphPath, content, "utf-8");
3443
3125
  }
3444
3126
  async function updateGraphFilesForTask(directory, taskId, files) {
3445
3127
  for (const file of files) {
@@ -3452,9 +3134,9 @@ async function updateGraphFilesForTask(directory, taskId, files) {
3452
3134
  }
3453
3135
  async function replaceGraphCalls(directory, filePath, calls, dependsOn) {
3454
3136
  const filename = pathToGraphFilename(filePath);
3455
- const graphPath = join3(directory, "Manifold", "graph", filename);
3137
+ const graphPath = join2(directory, "Manifold", "graph", filename);
3456
3138
  let entry;
3457
- if (existsSync3(graphPath)) {
3139
+ if (existsSync2(graphPath)) {
3458
3140
  const existing = await readGraphFile(directory, filePath);
3459
3141
  entry = existing || {
3460
3142
  filePath,
@@ -3473,20 +3155,20 @@ async function replaceGraphCalls(directory, filePath, calls, dependsOn) {
3473
3155
  entry.calls = [...new Set(calls)];
3474
3156
  entry.dependsOn = [...new Set(dependsOn)];
3475
3157
  const graphDir = dirname2(graphPath);
3476
- if (!existsSync3(graphDir)) {
3158
+ if (!existsSync2(graphDir)) {
3477
3159
  await mkdir2(graphDir, { recursive: true });
3478
3160
  }
3479
3161
  const content = formatGraphContent(entry);
3480
- await writeFile3(graphPath, content, "utf-8");
3162
+ await writeFile2(graphPath, content, "utf-8");
3481
3163
  }
3482
3164
 
3483
3165
  // src/graph-sync.ts
3484
3166
  import Database from "better-sqlite3";
3485
- import { existsSync as existsSync4 } from "fs";
3486
- import { join as join4 } from "path";
3167
+ import { existsSync as existsSync3 } from "fs";
3168
+ import { join as join3 } from "path";
3487
3169
  function openIndexDb(projectRoot) {
3488
- const dbPath = join4(projectRoot, ".opencode", "index", "codebase.db");
3489
- if (!existsSync4(dbPath)) {
3170
+ const dbPath = join3(projectRoot, ".opencode", "index", "codebase.db");
3171
+ if (!existsSync3(dbPath)) {
3490
3172
  return null;
3491
3173
  }
3492
3174
  try {
@@ -3574,9 +3256,9 @@ async function syncGraphFilesFromIndex(projectRoot, files) {
3574
3256
 
3575
3257
  // src/state-machine.ts
3576
3258
  async function readState(directory) {
3577
- const statePath = join5(directory, "Manifold", "state.json");
3578
- if (existsSync5(statePath)) {
3579
- const content = await readFile4(statePath, "utf-8");
3259
+ const statePath = join4(directory, "Manifold", "state.json");
3260
+ if (existsSync4(statePath)) {
3261
+ const content = await readFile3(statePath, "utf-8");
3580
3262
  return JSON.parse(content);
3581
3263
  }
3582
3264
  return {
@@ -3592,8 +3274,8 @@ async function readState(directory) {
3592
3274
  };
3593
3275
  }
3594
3276
  async function writeState(directory, state) {
3595
- const statePath = join5(directory, "Manifold", "state.json");
3596
- await writeFile4(statePath, JSON.stringify(state, null, 2));
3277
+ const statePath = join4(directory, "Manifold", "state.json");
3278
+ await writeFile3(statePath, JSON.stringify(state, null, 2));
3597
3279
  }
3598
3280
  function buildLoopHistory(state) {
3599
3281
  if (state.loop_history.length === 0) {
@@ -3605,16 +3287,16 @@ ${entry}`).join(`
3605
3287
  `);
3606
3288
  }
3607
3289
  async function readRecentTaskLogs(directory, count) {
3608
- const tasksDir = join5(directory, "Manifold", "tasks");
3609
- if (!existsSync5(tasksDir)) {
3290
+ const tasksDir = join4(directory, "Manifold", "tasks");
3291
+ if (!existsSync4(tasksDir)) {
3610
3292
  return [];
3611
3293
  }
3612
3294
  try {
3613
- const files = await readdir3(tasksDir);
3295
+ const files = await readdir2(tasksDir);
3614
3296
  const mdFiles = files.filter((f) => f.endsWith(".md")).sort();
3615
3297
  const recentFiles = mdFiles.slice(-count);
3616
3298
  const tasks = await Promise.all(recentFiles.map(async (filename) => {
3617
- const content = await readFile4(join5(tasksDir, filename), "utf-8");
3299
+ const content = await readFile3(join4(tasksDir, filename), "utf-8");
3618
3300
  return { filename, content };
3619
3301
  }));
3620
3302
  return tasks;
@@ -4322,9 +4004,9 @@ function setPluginContext(client) {
4322
4004
  pluginClient = client;
4323
4005
  }
4324
4006
  async function readSettings(directory) {
4325
- const settingsPath = join6(directory, "Manifold", "settings.json");
4326
- if (existsSync6(settingsPath)) {
4327
- const content = await readFile5(settingsPath, "utf-8");
4007
+ const settingsPath = join5(directory, "Manifold", "settings.json");
4008
+ if (existsSync5(settingsPath)) {
4009
+ const content = await readFile4(settingsPath, "utf-8");
4328
4010
  return JSON.parse(content);
4329
4011
  }
4330
4012
  return {
@@ -4339,10 +4021,10 @@ async function readSettings(directory) {
4339
4021
  };
4340
4022
  }
4341
4023
  async function updatePlansRegistry(directory, planFile) {
4342
- const plansPath = join6(directory, "Manifold", "plans.json");
4024
+ const plansPath = join5(directory, "Manifold", "plans.json");
4343
4025
  let plans = {};
4344
- if (existsSync6(plansPath)) {
4345
- const content = await readFile5(plansPath, "utf-8");
4026
+ if (existsSync5(plansPath)) {
4027
+ const content = await readFile4(plansPath, "utf-8");
4346
4028
  plans = JSON.parse(content);
4347
4029
  }
4348
4030
  const planSlug = planFile.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase().substring(0, 30);
@@ -4356,7 +4038,7 @@ async function updatePlansRegistry(directory, planFile) {
4356
4038
  };
4357
4039
  }
4358
4040
  plans[planSlug].task_count++;
4359
- await writeFile5(plansPath, JSON.stringify(plans, null, 2));
4041
+ await writeFile4(plansPath, JSON.stringify(plans, null, 2));
4360
4042
  return plans[planSlug].task_count;
4361
4043
  }
4362
4044
  function getClient() {
@@ -4466,31 +4148,10 @@ var ManifoldPlugin = async (ctx) => {
4466
4148
  return {
4467
4149
  tool: {
4468
4150
  dispatchTask: dispatchTaskTool
4469
- },
4470
- "command.execute.before": async (input, output) => {
4471
- if (input.command === "manifold-init") {
4472
- const initialized = await initProject(ctx.directory, ctx.client);
4473
- if (initialized.length > 0) {
4474
- output.parts = [
4475
- {
4476
- type: "text",
4477
- text: `Manifold initialized: ${initialized.join(", ")}`
4478
- }
4479
- ];
4480
- } else {
4481
- output.parts = [
4482
- {
4483
- type: "text",
4484
- text: "All Manifold files already present. To reset a specific component, delete the corresponding file(s) from `.opencode/agents/`, `.opencode/skills/`, or `Manifold/`, then run `/manifold-init` again."
4485
- }
4486
- ];
4487
- }
4488
- }
4489
4151
  }
4490
4152
  };
4491
4153
  };
4492
4154
  var server = ManifoldPlugin;
4493
4155
  export {
4494
- tui,
4495
4156
  server
4496
4157
  };