motifcode 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,8 +36,27 @@ motif # interactive session in the current dir
36
36
  motif --continue # with the latest conversation here loaded
37
37
  motif "fix the failing test in tests/" # one task, then exit
38
38
  motif -p "what does src/loop.ts do?" # print only the reply, for pipes
39
+ motif -p -- "--help" # pass a flag-looking task literally: -- ends option parsing
39
40
  ```
40
41
 
42
+ A standalone `--` ends flag and subcommand recognition. Everything after it is
43
+ the task, so `motif -p -- "--help"` asks about `--help` instead of printing CLI
44
+ help (plain `motif --help` still prints help).
45
+
46
+ One-shot and print runs ask before executing tools that require approval. The
47
+ prompt goes to stderr when stdin and stderr are terminals, so print stdout
48
+ contains only the final answer. Without an approval terminal, those calls are
49
+ refused. Use `--permissions auto` for unattended runs where you intend to
50
+ authorize those calls.
51
+
52
+ One-shot and print runs save their session records in `.motif/sessions/`.
53
+ Use `--journal <path>` to choose an output file. In print mode (`-p`), the
54
+ path must be new. An existing path is preserved and the command exits before
55
+ sending a model request. One-shot callers can also provide a prepared empty
56
+ file or a symlink to it. Records include events, checkpoints and the run's
57
+ ending. An interrupted run keeps its last checkpoint for
58
+ `motif resume <file> -p`. Journal failures go to stderr and exit nonzero.
59
+
41
60
  Connect MCP servers and check them from the CLI:
42
61
 
43
62
  ```bash
@@ -83,6 +102,10 @@ connectors still require their original host. Clear plugin setup requests load
83
102
  [skills guide](https://github.com/TaewoooPark/Motifcode/blob/main/docs/skills.md)
84
103
  for selection, scope, updates and compatibility limits.
85
104
 
105
+ Pressing Esc during an active `term` call stops the shell and its running commands.
106
+ The next `term` call starts a fresh shell, so the previous shell's working
107
+ directory and environment changes are lost.
108
+
86
109
  Needs Node 20.3+. The bundle is a single file with no runtime dependencies.
87
110
 
88
111
  Full documentation, the design notes on why this harness is shaped the way it is, and the Korean
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.5.0",
3
- "bytes": 2775935,
2
+ "version": "0.5.2",
3
+ "bytes": 2784005,
4
4
  "node": "v22.23.5"
5
5
  }
package/dist/motif.js CHANGED
@@ -7971,11 +7971,11 @@ var require_codegen = __commonJS({
7971
7971
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
7972
7972
  return `${varKind} ${this.name}${rhs};` + _n;
7973
7973
  }
7974
- optimizeNames(names, constants2) {
7974
+ optimizeNames(names, constants3) {
7975
7975
  if (!names[this.name.str])
7976
7976
  return;
7977
7977
  if (this.rhs)
7978
- this.rhs = optimizeExpr(this.rhs, names, constants2);
7978
+ this.rhs = optimizeExpr(this.rhs, names, constants3);
7979
7979
  return this;
7980
7980
  }
7981
7981
  get names() {
@@ -7992,10 +7992,10 @@ var require_codegen = __commonJS({
7992
7992
  render({ _n }) {
7993
7993
  return `${this.lhs} = ${this.rhs};` + _n;
7994
7994
  }
7995
- optimizeNames(names, constants2) {
7995
+ optimizeNames(names, constants3) {
7996
7996
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
7997
7997
  return;
7998
- this.rhs = optimizeExpr(this.rhs, names, constants2);
7998
+ this.rhs = optimizeExpr(this.rhs, names, constants3);
7999
7999
  return this;
8000
8000
  }
8001
8001
  get names() {
@@ -8056,8 +8056,8 @@ var require_codegen = __commonJS({
8056
8056
  optimizeNodes() {
8057
8057
  return `${this.code}` ? this : void 0;
8058
8058
  }
8059
- optimizeNames(names, constants2) {
8060
- this.code = optimizeExpr(this.code, names, constants2);
8059
+ optimizeNames(names, constants3) {
8060
+ this.code = optimizeExpr(this.code, names, constants3);
8061
8061
  return this;
8062
8062
  }
8063
8063
  get names() {
@@ -8086,12 +8086,12 @@ var require_codegen = __commonJS({
8086
8086
  }
8087
8087
  return nodes.length > 0 ? this : void 0;
8088
8088
  }
8089
- optimizeNames(names, constants2) {
8089
+ optimizeNames(names, constants3) {
8090
8090
  const { nodes } = this;
8091
8091
  let i = nodes.length;
8092
8092
  while (i--) {
8093
8093
  const n = nodes[i];
8094
- if (n.optimizeNames(names, constants2))
8094
+ if (n.optimizeNames(names, constants3))
8095
8095
  continue;
8096
8096
  subtractNames(names, n.names);
8097
8097
  nodes.splice(i, 1);
@@ -8144,12 +8144,12 @@ var require_codegen = __commonJS({
8144
8144
  return void 0;
8145
8145
  return this;
8146
8146
  }
8147
- optimizeNames(names, constants2) {
8147
+ optimizeNames(names, constants3) {
8148
8148
  var _a3;
8149
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
8150
- if (!(super.optimizeNames(names, constants2) || this.else))
8149
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants3);
8150
+ if (!(super.optimizeNames(names, constants3) || this.else))
8151
8151
  return;
8152
- this.condition = optimizeExpr(this.condition, names, constants2);
8152
+ this.condition = optimizeExpr(this.condition, names, constants3);
8153
8153
  return this;
8154
8154
  }
8155
8155
  get names() {
@@ -8172,10 +8172,10 @@ var require_codegen = __commonJS({
8172
8172
  render(opts) {
8173
8173
  return `for(${this.iteration})` + super.render(opts);
8174
8174
  }
8175
- optimizeNames(names, constants2) {
8176
- if (!super.optimizeNames(names, constants2))
8175
+ optimizeNames(names, constants3) {
8176
+ if (!super.optimizeNames(names, constants3))
8177
8177
  return;
8178
- this.iteration = optimizeExpr(this.iteration, names, constants2);
8178
+ this.iteration = optimizeExpr(this.iteration, names, constants3);
8179
8179
  return this;
8180
8180
  }
8181
8181
  get names() {
@@ -8211,10 +8211,10 @@ var require_codegen = __commonJS({
8211
8211
  render(opts) {
8212
8212
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
8213
8213
  }
8214
- optimizeNames(names, constants2) {
8215
- if (!super.optimizeNames(names, constants2))
8214
+ optimizeNames(names, constants3) {
8215
+ if (!super.optimizeNames(names, constants3))
8216
8216
  return;
8217
- this.iterable = optimizeExpr(this.iterable, names, constants2);
8217
+ this.iterable = optimizeExpr(this.iterable, names, constants3);
8218
8218
  return this;
8219
8219
  }
8220
8220
  get names() {
@@ -8256,11 +8256,11 @@ var require_codegen = __commonJS({
8256
8256
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
8257
8257
  return this;
8258
8258
  }
8259
- optimizeNames(names, constants2) {
8259
+ optimizeNames(names, constants3) {
8260
8260
  var _a3, _b;
8261
- super.optimizeNames(names, constants2);
8262
- (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
8263
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants2);
8261
+ super.optimizeNames(names, constants3);
8262
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants3);
8263
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants3);
8264
8264
  return this;
8265
8265
  }
8266
8266
  get names() {
@@ -8561,7 +8561,7 @@ var require_codegen = __commonJS({
8561
8561
  function addExprNames(names, from) {
8562
8562
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
8563
8563
  }
8564
- function optimizeExpr(expr, names, constants2) {
8564
+ function optimizeExpr(expr, names, constants3) {
8565
8565
  if (expr instanceof code_1.Name)
8566
8566
  return replaceName(expr);
8567
8567
  if (!canOptimize(expr))
@@ -8576,14 +8576,14 @@ var require_codegen = __commonJS({
8576
8576
  return items;
8577
8577
  }, []));
8578
8578
  function replaceName(n) {
8579
- const c = constants2[n.str];
8579
+ const c = constants3[n.str];
8580
8580
  if (c === void 0 || names[n.str] !== 1)
8581
8581
  return n;
8582
8582
  delete names[n.str];
8583
8583
  return c;
8584
8584
  }
8585
8585
  function canOptimize(e) {
8586
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants2[c.str] !== void 0);
8586
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants3[c.str] !== void 0);
8587
8587
  }
8588
8588
  }
8589
8589
  function subtractNames(names, from) {
@@ -16261,7 +16261,7 @@ var init_operation = __esm({
16261
16261
 
16262
16262
  // packages/mcp/src/auth-store.ts
16263
16263
  import { createHash as createHash6, randomBytes } from "node:crypto";
16264
- import { closeSync as closeSync2, constants, existsSync as existsSync10, fstatSync as fstatSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync5, openSync as openSync2, readFileSync as readFileSync9, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
16264
+ import { closeSync as closeSync3, constants as constants2, existsSync as existsSync10, fstatSync as fstatSync3, lstatSync as lstatSync2, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync9, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "node:fs";
16265
16265
  import { homedir as homedir5 } from "node:os";
16266
16266
  import { join as join11 } from "node:path";
16267
16267
  var McpAuthError, storageError, authKey, McpAuthStore;
@@ -16292,15 +16292,15 @@ var init_auth_store = __esm({
16292
16292
  try {
16293
16293
  if (!existsSync10(file)) return void 0;
16294
16294
  if (lstatSync2(this.directory).isSymbolicLink()) throw storageError();
16295
- const fd = openSync2(file, constants.O_RDONLY | constants.O_NOFOLLOW);
16295
+ const fd = openSync3(file, constants2.O_RDONLY | constants2.O_NOFOLLOW);
16296
16296
  try {
16297
- const stat = fstatSync2(fd);
16297
+ const stat = fstatSync3(fd);
16298
16298
  if (!stat.isFile() || stat.size > 256 * 1024 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw storageError();
16299
16299
  const value = JSON.parse(readFileSync9(fd, "utf8"));
16300
16300
  if (value.version !== 1 || value.key !== key || typeof value.endpoint !== "string" || typeof value.revision !== "string") throw storageError();
16301
16301
  return value;
16302
16302
  } finally {
16303
- closeSync2(fd);
16303
+ closeSync3(fd);
16304
16304
  }
16305
16305
  } catch {
16306
16306
  throw storageError();
@@ -16331,7 +16331,7 @@ var init_auth_store = __esm({
16331
16331
  let temporary;
16332
16332
  try {
16333
16333
  temporary = `${file}.${randomBytes(12).toString("hex")}.tmp`;
16334
- writeFileSync4(temporary, JSON.stringify(record3), { flag: "wx", mode: 384 });
16334
+ writeFileSync5(temporary, JSON.stringify(record3), { flag: "wx", mode: 384 });
16335
16335
  renameSync2(temporary, file);
16336
16336
  } catch (error3) {
16337
16337
  if (error3 instanceof McpAuthError) throw error3;
@@ -30016,9 +30016,9 @@ var init_ajvProvider_97rDpkRx = __esm({
30016
30016
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
30017
30017
  return `${varKind} ${this.name}${rhs};` + _n;
30018
30018
  }
30019
- optimizeNames(names, constants2) {
30019
+ optimizeNames(names, constants3) {
30020
30020
  if (!names[this.name.str]) return;
30021
- if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants2);
30021
+ if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants3);
30022
30022
  return this;
30023
30023
  }
30024
30024
  get names() {
@@ -30035,9 +30035,9 @@ var init_ajvProvider_97rDpkRx = __esm({
30035
30035
  render({ _n }) {
30036
30036
  return `${this.lhs} = ${this.rhs};` + _n;
30037
30037
  }
30038
- optimizeNames(names, constants2) {
30038
+ optimizeNames(names, constants3) {
30039
30039
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return;
30040
- this.rhs = optimizeExpr(this.rhs, names, constants2);
30040
+ this.rhs = optimizeExpr(this.rhs, names, constants3);
30041
30041
  return this;
30042
30042
  }
30043
30043
  get names() {
@@ -30096,8 +30096,8 @@ var init_ajvProvider_97rDpkRx = __esm({
30096
30096
  optimizeNodes() {
30097
30097
  return `${this.code}` ? this : void 0;
30098
30098
  }
30099
- optimizeNames(names, constants2) {
30100
- this.code = optimizeExpr(this.code, names, constants2);
30099
+ optimizeNames(names, constants3) {
30100
+ this.code = optimizeExpr(this.code, names, constants3);
30101
30101
  return this;
30102
30102
  }
30103
30103
  get names() {
@@ -30123,12 +30123,12 @@ var init_ajvProvider_97rDpkRx = __esm({
30123
30123
  }
30124
30124
  return nodes.length > 0 ? this : void 0;
30125
30125
  }
30126
- optimizeNames(names, constants2) {
30126
+ optimizeNames(names, constants3) {
30127
30127
  const { nodes } = this;
30128
30128
  let i = nodes.length;
30129
30129
  while (i--) {
30130
30130
  const n = nodes[i];
30131
- if (n.optimizeNames(names, constants2)) continue;
30131
+ if (n.optimizeNames(names, constants3)) continue;
30132
30132
  subtractNames(names, n.names);
30133
30133
  nodes.splice(i, 1);
30134
30134
  }
@@ -30175,11 +30175,11 @@ var init_ajvProvider_97rDpkRx = __esm({
30175
30175
  if (cond === false || !this.nodes.length) return void 0;
30176
30176
  return this;
30177
30177
  }
30178
- optimizeNames(names, constants2) {
30178
+ optimizeNames(names, constants3) {
30179
30179
  var _a3;
30180
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
30181
- if (!(super.optimizeNames(names, constants2) || this.else)) return;
30182
- this.condition = optimizeExpr(this.condition, names, constants2);
30180
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants3);
30181
+ if (!(super.optimizeNames(names, constants3) || this.else)) return;
30182
+ this.condition = optimizeExpr(this.condition, names, constants3);
30183
30183
  return this;
30184
30184
  }
30185
30185
  get names() {
@@ -30201,9 +30201,9 @@ var init_ajvProvider_97rDpkRx = __esm({
30201
30201
  render(opts) {
30202
30202
  return `for(${this.iteration})` + super.render(opts);
30203
30203
  }
30204
- optimizeNames(names, constants2) {
30205
- if (!super.optimizeNames(names, constants2)) return;
30206
- this.iteration = optimizeExpr(this.iteration, names, constants2);
30204
+ optimizeNames(names, constants3) {
30205
+ if (!super.optimizeNames(names, constants3)) return;
30206
+ this.iteration = optimizeExpr(this.iteration, names, constants3);
30207
30207
  return this;
30208
30208
  }
30209
30209
  get names() {
@@ -30238,9 +30238,9 @@ var init_ajvProvider_97rDpkRx = __esm({
30238
30238
  render(opts) {
30239
30239
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
30240
30240
  }
30241
- optimizeNames(names, constants2) {
30242
- if (!super.optimizeNames(names, constants2)) return;
30243
- this.iterable = optimizeExpr(this.iterable, names, constants2);
30241
+ optimizeNames(names, constants3) {
30242
+ if (!super.optimizeNames(names, constants3)) return;
30243
+ this.iterable = optimizeExpr(this.iterable, names, constants3);
30244
30244
  return this;
30245
30245
  }
30246
30246
  get names() {
@@ -30279,11 +30279,11 @@ var init_ajvProvider_97rDpkRx = __esm({
30279
30279
  (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes();
30280
30280
  return this;
30281
30281
  }
30282
- optimizeNames(names, constants2) {
30282
+ optimizeNames(names, constants3) {
30283
30283
  var _a3, _b;
30284
- super.optimizeNames(names, constants2);
30285
- (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNames(names, constants2);
30286
- (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants2);
30284
+ super.optimizeNames(names, constants3);
30285
+ (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNames(names, constants3);
30286
+ (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants3);
30287
30287
  return this;
30288
30288
  }
30289
30289
  get names() {
@@ -30532,7 +30532,7 @@ var init_ajvProvider_97rDpkRx = __esm({
30532
30532
  function addExprNames(names, from) {
30533
30533
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
30534
30534
  }
30535
- function optimizeExpr(expr, names, constants2) {
30535
+ function optimizeExpr(expr, names, constants3) {
30536
30536
  if (expr instanceof code_1.Name) return replaceName(expr);
30537
30537
  if (!canOptimize(expr)) return expr;
30538
30538
  return new code_1._Code(expr._items.reduce((items, c) => {
@@ -30542,13 +30542,13 @@ var init_ajvProvider_97rDpkRx = __esm({
30542
30542
  return items;
30543
30543
  }, []));
30544
30544
  function replaceName(n) {
30545
- const c = constants2[n.str];
30545
+ const c = constants3[n.str];
30546
30546
  if (c === void 0 || names[n.str] !== 1) return n;
30547
30547
  delete names[n.str];
30548
30548
  return c;
30549
30549
  }
30550
30550
  function canOptimize(e) {
30551
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants2[c.str] !== void 0);
30551
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants3[c.str] !== void 0);
30552
30552
  }
30553
30553
  }
30554
30554
  function subtractNames(names, from) {
@@ -46193,6 +46193,7 @@ var init_client = __esm({
46193
46193
  });
46194
46194
 
46195
46195
  // packages/cli/src/main.ts
46196
+ import { randomUUID as randomUUID5 } from "node:crypto";
46196
46197
  import { existsSync as existsSync17, readFileSync as readFileSync18, readdirSync as readdirSync7 } from "node:fs";
46197
46198
  import { homedir as homedir12 } from "node:os";
46198
46199
  import { join as join18 } from "node:path";
@@ -50146,7 +50147,7 @@ var DEFAULT_HOOKS = Object.freeze({
50146
50147
  });
50147
50148
 
50148
50149
  // packages/journal/src/index.ts
50149
- import { appendFileSync, existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
50150
+ import { closeSync, constants, existsSync as existsSync4, fstatSync, mkdirSync as mkdirSync3, openSync, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
50150
50151
  import { dirname as dirname3, join as join4 } from "node:path";
50151
50152
 
50152
50153
  // packages/journal/src/distil.ts
@@ -50488,23 +50489,40 @@ function redactJournal(text) {
50488
50489
  }
50489
50490
 
50490
50491
  // packages/journal/src/index.ts
50492
+ var APPEND_EXISTING = constants.O_WRONLY | constants.O_APPEND;
50491
50493
  var Journal = class {
50492
- constructor(path, header) {
50494
+ constructor(path, header, options = {}) {
50493
50495
  this.path = path;
50494
50496
  this.header = header;
50497
+ this.options = options;
50495
50498
  mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
50496
50499
  }
50497
50500
  path;
50498
50501
  header;
50502
+ options;
50499
50503
  headerWritten = false;
50500
50504
  seq = 0;
50501
- write(line2) {
50502
- appendFileSync(this.path, JSON.stringify(line2) + "\n", { encoding: "utf8", mode: 384 });
50505
+ expectedFile;
50506
+ write(line2, flags = APPEND_EXISTING) {
50507
+ const data = Buffer.from(JSON.stringify(line2) + "\n", "utf8");
50508
+ const file = openSync(this.path, flags, 384);
50509
+ try {
50510
+ const { dev, ino, size } = fstatSync(file, { bigint: true });
50511
+ const expected = this.expectedFile;
50512
+ if (expected && (dev !== expected.dev || ino !== expected.ino || size !== expected.size)) {
50513
+ throw new Error(`Journal changed during the run: ${this.path}`);
50514
+ }
50515
+ writeFileSync3(file, data);
50516
+ this.expectedFile = { dev, ino, size: size + BigInt(data.length) };
50517
+ } finally {
50518
+ closeSync(file);
50519
+ }
50503
50520
  }
50504
50521
  ensureHeader() {
50505
50522
  if (this.headerWritten) return;
50523
+ const flags = APPEND_EXISTING | constants.O_CREAT | (this.options.allowExisting ? 0 : constants.O_EXCL);
50524
+ this.write({ t: "header", header: this.header }, flags);
50506
50525
  this.headerWritten = true;
50507
- this.write({ t: "header", header: this.header });
50508
50526
  }
50509
50527
  record(scope, record3) {
50510
50528
  this.ensureHeader();
@@ -52187,7 +52205,7 @@ function renderCellRaw(cell, opts) {
52187
52205
  breakage_limit: "Stopped: too many malformed actions",
52188
52206
  loop_detected: "Stopped: the same action kept repeating",
52189
52207
  no_action_limit: "Stopped: no action for several turns",
52190
- transport_error: "Stopped: the endpoint could not be reached"
52208
+ transport_error: "Stopped: the request did not complete"
52191
52209
  };
52192
52210
  return [line(` ${RESULT} ${label3[cell.reason] ?? `Stopped: ${cell.reason}`}`, "warn"), blank];
52193
52211
  }
@@ -52580,6 +52598,8 @@ var Composer = class {
52580
52598
  browsing = null;
52581
52599
  /** The unsent text set aside while browsing history, restored on the way back. */
52582
52600
  draft = [];
52601
+ /** Cursor position inside that draft, restored with it. */
52602
+ draftCursor = 0;
52583
52603
  get text() {
52584
52604
  return this.chars.join("");
52585
52605
  }
@@ -52731,6 +52751,7 @@ var Composer = class {
52731
52751
  if (this.history.length === 0) return false;
52732
52752
  if (this.browsing === null) {
52733
52753
  this.draft = [...this.chars];
52754
+ this.draftCursor = this.pos;
52734
52755
  this.browsing = this.history.length - 1;
52735
52756
  } else if (this.browsing > 0) {
52736
52757
  this.browsing -= 1;
@@ -52746,11 +52767,12 @@ var Composer = class {
52746
52767
  if (this.browsing < this.history.length - 1) {
52747
52768
  this.browsing += 1;
52748
52769
  this.chars = [...this.history[this.browsing]];
52749
- } else {
52750
- this.browsing = null;
52751
- this.chars = [...this.draft];
52770
+ this.pos = this.chars.length;
52771
+ return true;
52752
52772
  }
52753
- this.pos = this.chars.length;
52773
+ this.browsing = null;
52774
+ this.chars = [...this.draft];
52775
+ this.pos = Math.min(this.draftCursor, this.chars.length);
52754
52776
  return true;
52755
52777
  }
52756
52778
  lineStart(from) {
@@ -52975,16 +52997,37 @@ function renderPanel(view, opts) {
52975
52997
  function mentionAt(text, cursor) {
52976
52998
  const chars = [...text];
52977
52999
  const at = Math.min(cursor, chars.length);
53000
+ let end = at;
53001
+ while (end < chars.length && !/\s/.test(chars[end])) end++;
53002
+ const directory = /(?:^|\s)(@"((?:[^"\\\n]|\\.)*\/)"(\S*))$/.exec(chars.slice(0, at).join(""));
53003
+ if (directory) {
53004
+ return {
53005
+ start: at - [...directory[1]].length,
53006
+ end,
53007
+ query: decodeQuotedPath(directory[2]) + directory[3]
53008
+ };
53009
+ }
52978
53010
  let start = at;
52979
53011
  while (start > 0 && !/\s/.test(chars[start - 1])) start--;
52980
53012
  if (chars[start] !== "@") return null;
52981
- let end = at;
52982
- while (end < chars.length && !/\s/.test(chars[end])) end++;
52983
53013
  return { start, end, query: chars.slice(start + 1, at).join("") };
52984
53014
  }
52985
- function mentionsIn(text) {
53015
+ function stripMentionPunctuation(value) {
53016
+ return value.replace(/[.,;:!?)]+$/, "");
53017
+ }
53018
+ function formatMention(path) {
53019
+ if (!/[\s"]/.test(path) && stripMentionPunctuation(path) === path) return path;
53020
+ return `"${path.replace(/[\\"]/g, (c) => `\\${c}`)}"`;
53021
+ }
53022
+ function decodeQuotedPath(path) {
53023
+ return path.replace(/\\(["\\])/g, "$1");
53024
+ }
53025
+ function parseMentions(text) {
52986
53026
  const out = [];
52987
- for (const m of text.matchAll(/(?:^|\s)@(\S+)/g)) out.push(m[1]);
53027
+ for (const [, encoded, plain] of text.matchAll(/(?:^|\s)@(?:"((?:[^"\\\n]|\\.)+)"(?=$|\s)|(\S+))/g)) {
53028
+ if (encoded === void 0) out.push({ value: plain, quoted: false });
53029
+ else out.push({ value: decodeQuotedPath(encoded), quoted: true });
53030
+ }
52988
53031
  return out;
52989
53032
  }
52990
53033
 
@@ -53239,6 +53282,14 @@ var Screen = class {
53239
53282
  get interactiveInput() {
53240
53283
  return this.detachInput !== null;
53241
53284
  }
53285
+ /** Make room for a line prompt that temporarily owns terminal input. */
53286
+ suspendInput() {
53287
+ if (!this.detachInput) return;
53288
+ this.closeOutputView();
53289
+ this.detachInput();
53290
+ this.detachInput = null;
53291
+ this.clearFooter();
53292
+ }
53242
53293
  toggleThinking() {
53243
53294
  const before = this.renderOptions;
53244
53295
  this.showThinking = !this.showThinking;
@@ -53817,7 +53868,7 @@ var Screen = class {
53817
53868
  };
53818
53869
 
53819
53870
  // packages/cli/src/chat.ts
53820
- import { appendFileSync as appendFileSync2, existsSync as existsSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync11, realpathSync as realpathSync8, statSync as statSync6 } from "node:fs";
53871
+ import { appendFileSync, existsSync as existsSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync11, realpathSync as realpathSync8, statSync as statSync6 } from "node:fs";
53821
53872
  import { homedir as homedir6 } from "node:os";
53822
53873
  import { dirname as dirname9, join as join12, resolve as resolve13 } from "node:path";
53823
53874
 
@@ -53906,20 +53957,25 @@ function matchFiles(entries, query, limit = 8) {
53906
53957
  return entries.map((e) => ({ e, s: scorePath(e.path, query) })).filter((x) => x.s > 0).sort((a, b) => b.s - a.s || a.e.path.length - b.e.path.length || a.e.path.localeCompare(b.e.path)).slice(0, limit).map((x) => x.e);
53907
53958
  }
53908
53959
  var ATTACH_CAP_BYTES = 1e5;
53909
- function attachMention(token, opts) {
53910
- if (token.startsWith("skill:")) {
53960
+ function attachMention(mention, opts) {
53961
+ const { value: token, quoted } = typeof mention === "string" ? { value: mention, quoted: false } : mention;
53962
+ if (!quoted && token.startsWith("skill:")) {
53911
53963
  const body = opts.renderSkill?.(token.slice("skill:".length));
53912
53964
  return body ? { mention: token, block: body } : null;
53913
53965
  }
53914
- const clean2 = token.replace(/[.,;:!?)]+$/, "");
53966
+ const clean2 = quoted ? token : stripMentionPunctuation(token);
53915
53967
  const target = resolve5(opts.cwd, clean2);
53916
53968
  const rel = relative3(opts.cwd, target);
53917
53969
  if (rel.startsWith("..") || !existsSync6(target)) return null;
53918
53970
  const st = statSync3(target);
53919
53971
  if (st.isDirectory()) {
53920
- const names = readdirSync3(target).filter((n) => !SKIP_DIRS.has(n)).sort().slice(0, 200);
53972
+ const eligible = readdirSync3(target).filter((n) => !SKIP_DIRS.has(n)).sort();
53973
+ const names = eligible.slice(0, 200);
53974
+ const omitted = eligible.length - names.length;
53975
+ const note2 = omitted > 0 ? `
53976
+ \u2026 ${omitted} more ${omitted === 1 ? "entry" : "entries"}` : "";
53921
53977
  return { mention: clean2, block: `<directory path="${clean2}">
53922
- ${names.join("\n")}
53978
+ ${names.join("\n")}${note2}
53923
53979
  </directory>` };
53924
53980
  }
53925
53981
  const buf = readFileSync6(target);
@@ -54059,8 +54115,12 @@ function expandSkillInput(text, opts) {
54059
54115
  const loaded = opts.skills.load(slash[1], { invocation: "user", arguments: slash[2] ?? "", cwd: opts.cwd });
54060
54116
  return { task: loaded.output, attached: loaded.ok ? [`skill:${slash[1]}`] : [], errors: loaded.ok ? [] : [loaded.output] };
54061
54117
  }
54062
- const mentions = mentionsIn(text);
54063
- const explicit = new Set(mentions.filter((m) => m.startsWith("skill:")).map((m) => m.slice(6)));
54118
+ const fileMentions = [];
54119
+ const explicit = /* @__PURE__ */ new Set();
54120
+ for (const mention of parseMentions(text)) {
54121
+ if (!mention.quoted && mention.value.startsWith("skill:")) explicit.add(mention.value.slice(6));
54122
+ else fileMentions.push(mention);
54123
+ }
54064
54124
  for (const match of text.matchAll(/(?:^|\s)\$([\w][\w:-]*)\b/g)) if (opts.skills.get(match[1])) explicit.add(match[1]);
54065
54125
  const input = text.replace(/(^|\s)@skill:([^\s]+)/g, (match, prefix, name) => explicit.has(name) ? prefix : match).replace(/(^|\s)\$([\w][\w:-]*)(?=$|\s|[.,;!?])/g, (match, prefix, name) => explicit.has(name) ? prefix : match).trim();
54066
54126
  const errors = [];
@@ -54078,7 +54138,7 @@ function expandSkillInput(text, opts) {
54078
54138
  const result = opts.skills.load(name, { invocation: "model", cwd: opts.cwd });
54079
54139
  if (result.ok) bodies.set(name, result.output);
54080
54140
  }
54081
- const expanded = expandMentions(text, [...mentions.filter((m) => !m.startsWith("skill:")), ...[...bodies.keys()].map((n) => `skill:${n}`)], {
54141
+ const expanded = expandMentions(text, [...fileMentions, ...[...bodies.keys()].map((n) => `skill:${n}`)], {
54082
54142
  cwd: opts.cwd,
54083
54143
  renderSkill: (name) => bodies.get(name)
54084
54144
  });
@@ -54273,11 +54333,24 @@ var COMMANDS = [
54273
54333
  {
54274
54334
  name: "help",
54275
54335
  description: "commands and keys",
54276
- run: () => {
54336
+ usage: "[command]",
54337
+ run: (_ctx, args) => {
54338
+ const requested = args.trim().replace(/^\//, "");
54339
+ if (requested) {
54340
+ const command = findCommand(requested);
54341
+ if (!command) return fail(`/help ${requested}`, `unknown command /${requested} \u2014 /help lists them`);
54342
+ const invocation = `/${command.name}${command.usage ? ` ${command.usage}` : ""}`;
54343
+ return ok(invocation, [
54344
+ command.description,
54345
+ "",
54346
+ "Run /help with no argument for the command index and keys."
54347
+ ]);
54348
+ }
54277
54349
  const width = Math.max(...COMMANDS.map((c) => `/${c.name}${c.usage ? ` ${c.usage}` : ""}`.length));
54278
54350
  const lines = COMMANDS.map(
54279
54351
  (c) => `${`/${c.name}${c.usage ? ` ${c.usage}` : ""}`.padEnd(width)} ${c.description}`
54280
54352
  );
54353
+ lines.push("", "Give /help a command name for its usage: /help <command>.");
54281
54354
  lines.push("", "Skills are commands too: /<skill> [input] runs one \u2014 /skills lists them.");
54282
54355
  const keyWidth = Math.max(...KEYS.map(([k]) => k.length));
54283
54356
  lines.push("", "keys");
@@ -54730,7 +54803,7 @@ function parseConfigValue(field, raw) {
54730
54803
  }
54731
54804
 
54732
54805
  // packages/cli/src/insights.ts
54733
- import { closeSync, fstatSync, openSync, opendirSync, readSync, statSync as statSync4 } from "node:fs";
54806
+ import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, opendirSync, readSync, statSync as statSync4 } from "node:fs";
54734
54807
  import { join as join8, resolve as resolve6 } from "node:path";
54735
54808
  var MAX_ENTRIES = 1e4;
54736
54809
  var MAX_FILES = 200;
@@ -54863,9 +54936,9 @@ function collectInsights(journalDir, opts = {}) {
54863
54936
  for (const { path } of candidates.slice(0, MAX_FILES)) {
54864
54937
  let text;
54865
54938
  try {
54866
- const fd = openSync(path, "r");
54939
+ const fd = openSync2(path, "r");
54867
54940
  try {
54868
- const size = fstatSync(fd).size;
54941
+ const size = fstatSync2(fd).size;
54869
54942
  if (size > MAX_FILE_BYTES) {
54870
54943
  result.files.oversized++;
54871
54944
  continue;
@@ -54884,7 +54957,7 @@ function collectInsights(journalDir, opts = {}) {
54884
54957
  bytes += offset;
54885
54958
  text = buffer.subarray(0, offset).toString("utf8");
54886
54959
  } finally {
54887
- closeSync(fd);
54960
+ closeSync2(fd);
54888
54961
  }
54889
54962
  } catch {
54890
54963
  result.files.unreadable++;
@@ -55666,7 +55739,7 @@ function worstState(checks) {
55666
55739
 
55667
55740
  // packages/cli/src/executor.ts
55668
55741
  import { spawn as spawn2 } from "node:child_process";
55669
- import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "node:fs";
55742
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "node:fs";
55670
55743
  import { dirname as dirname5, resolve as resolve8 } from "node:path";
55671
55744
 
55672
55745
  // packages/cli/src/policy.ts
@@ -55755,7 +55828,8 @@ function readinessMarker(pid, generation) {
55755
55828
  }
55756
55829
  function readinessProbe(marker) {
55757
55830
  const split = marker.length >> 1;
55758
- return `echo "${marker.slice(0, split)}""${marker.slice(split)}"
55831
+ return `set +m 2>/dev/null || true
55832
+ echo "${marker.slice(0, split)}""${marker.slice(split)}"
55759
55833
  `;
55760
55834
  }
55761
55835
  var PersistentShell = class {
@@ -55783,6 +55857,7 @@ var PersistentShell = class {
55783
55857
  this.exited = false;
55784
55858
  this.exitCode = void 0;
55785
55859
  const capture = (c) => {
55860
+ if (this.proc !== proc) return;
55786
55861
  this.buffer += c.toString();
55787
55862
  if (this.buffer.length > 4e5) {
55788
55863
  const drop = this.buffer.length - 2e5;
@@ -55792,12 +55867,16 @@ var PersistentShell = class {
55792
55867
  };
55793
55868
  proc.stdout?.on("data", capture);
55794
55869
  proc.stderr?.on("data", capture);
55870
+ proc.stdin?.on("error", () => {
55871
+ if (this.proc === proc) this.close();
55872
+ });
55795
55873
  proc.on("exit", (code) => {
55874
+ if (this.proc !== proc) return;
55796
55875
  this.exited = true;
55797
55876
  this.exitCode = code ?? void 0;
55798
55877
  });
55799
55878
  proc.on("error", () => {
55800
- this.exited = true;
55879
+ if (this.proc === proc) this.exited = true;
55801
55880
  });
55802
55881
  this.proc = proc;
55803
55882
  this.ready = this.waitUntilStarted(proc, ++this.spawns);
@@ -55829,7 +55908,7 @@ var PersistentShell = class {
55829
55908
  proc.stdin?.write(readinessProbe(marker));
55830
55909
  const deadline2 = Date.now() + 1e4;
55831
55910
  while (Date.now() < deadline2) {
55832
- if (this.exited) return;
55911
+ if (this.proc !== proc || this.exited) return;
55833
55912
  const at = this.buffer.indexOf(marker, this.cursor);
55834
55913
  if (at !== -1) {
55835
55914
  const eol = this.buffer.indexOf("\n", at);
@@ -55844,21 +55923,35 @@ var PersistentShell = class {
55844
55923
  }
55845
55924
  /** Send keystrokes verbatim, wait, and return everything that arrived since. */
55846
55925
  async send(keystrokes, durationS, signal) {
55926
+ if (signal?.aborted) return { output: "", alive: this.alive, cancelled: true };
55847
55927
  const proc = this.ensure();
55848
- await this.ready;
55849
- if (keystrokes !== "") proc.stdin?.write(encodeKeystrokes(keystrokes));
55850
- const wait = Math.min(Math.max(durationS, 0), 60) * 1e3;
55851
- await new Promise((r) => {
55852
- const timer = setTimeout(done, wait);
55853
- const onAbort = () => done();
55854
- function done() {
55855
- clearTimeout(timer);
55856
- signal?.removeEventListener("abort", onAbort);
55857
- r();
55858
- }
55859
- if (signal?.aborted) done();
55860
- else signal?.addEventListener("abort", onAbort, { once: true });
55928
+ let timer;
55929
+ let stopWaiting = () => {
55930
+ };
55931
+ const cancelled2 = new Promise((resolve20) => {
55932
+ stopWaiting = resolve20;
55861
55933
  });
55934
+ const onAbort = () => {
55935
+ if (this.proc === proc) this.close();
55936
+ stopWaiting();
55937
+ };
55938
+ signal?.addEventListener("abort", onAbort, { once: true });
55939
+ try {
55940
+ await Promise.race([this.ready, cancelled2]);
55941
+ if (!signal?.aborted && this.proc === proc && !this.exited) {
55942
+ if (keystrokes !== "") proc.stdin?.write(encodeKeystrokes(keystrokes));
55943
+ const wait = Math.min(Math.max(durationS, 0), 60) * 1e3;
55944
+ const elapsed = new Promise((resolve20) => {
55945
+ timer = setTimeout(resolve20, wait);
55946
+ });
55947
+ await Promise.race([elapsed, cancelled2]);
55948
+ }
55949
+ } finally {
55950
+ clearTimeout(timer);
55951
+ signal?.removeEventListener("abort", onAbort);
55952
+ }
55953
+ if (signal?.aborted) return { output: "", alive: false, cancelled: true };
55954
+ if (this.proc !== proc) return { output: "", alive: false };
55862
55955
  const output = this.buffer.slice(this.cursor);
55863
55956
  this.cursor = this.buffer.length;
55864
55957
  return {
@@ -55869,6 +55962,9 @@ var PersistentShell = class {
55869
55962
  }
55870
55963
  close() {
55871
55964
  const pid = this.proc?.pid;
55965
+ this.proc = null;
55966
+ this.ready = null;
55967
+ this.exited = true;
55872
55968
  if (pid !== void 0) {
55873
55969
  try {
55874
55970
  process.kill(-pid, "SIGKILL");
@@ -55879,8 +55975,6 @@ var PersistentShell = class {
55879
55975
  }
55880
55976
  }
55881
55977
  }
55882
- this.proc = null;
55883
- this.exited = true;
55884
55978
  }
55885
55979
  };
55886
55980
  async function runBash(command, cwd, timeoutMs, policy, scratch, signal) {
@@ -55936,8 +56030,8 @@ function writeFile(path, content, cwd) {
55936
56030
  const target = resolve8(cwd, path);
55937
56031
  mkdirSync4(dirname5(target), { recursive: true });
55938
56032
  const existed = existsSync8(target);
55939
- writeFileSync3(target, content, "utf8");
55940
- const lines = content === "" ? 0 : content.split("\n").length;
56033
+ writeFileSync4(target, content, "utf8");
56034
+ const lines = toLogicalLines(content).length;
55941
56035
  return {
55942
56036
  ok: true,
55943
56037
  output: `${existed ? "replaced" : "created"} ${path} (${lines} lines, ${Buffer.byteLength(content, "utf8")} bytes)`
@@ -56057,6 +56151,12 @@ var ToolExecutor = class {
56057
56151
  );
56058
56152
  case "term": {
56059
56153
  const r = await this.shell.send(str2(args, "keystrokes"), num(args, "duration_s") ?? 1, signal);
56154
+ if (r.cancelled) {
56155
+ return {
56156
+ ok: false,
56157
+ output: "Terminal call cancelled. The next `term` call will start a fresh shell."
56158
+ };
56159
+ }
56060
56160
  if (!r.alive) {
56061
56161
  return {
56062
56162
  ok: false,
@@ -58629,7 +58729,7 @@ async function requestMcpInteraction(request, ui) {
58629
58729
 
58630
58730
  // packages/cli/src/mcp-config-edit.ts
58631
58731
  import { randomUUID as randomUUID3 } from "node:crypto";
58632
- import { closeSync as closeSync3, fstatSync as fstatSync3, fsyncSync, lstatSync as lstatSync3, mkdirSync as mkdirSync6, openSync as openSync3, readFileSync as readFileSync10, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync5 } from "node:fs";
58732
+ import { closeSync as closeSync4, fstatSync as fstatSync4, fsyncSync, lstatSync as lstatSync3, mkdirSync as mkdirSync6, openSync as openSync4, readFileSync as readFileSync10, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync6 } from "node:fs";
58633
58733
  import { dirname as dirname8, resolve as resolve12 } from "node:path";
58634
58734
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
58635
58735
  var McpConfigEditError = class extends Error {
@@ -58696,12 +58796,12 @@ function updateMcpConfig(options, update) {
58696
58796
  try {
58697
58797
  mkdirSync6(directory, { recursive: true, mode: 448 });
58698
58798
  try {
58699
- lock = openSync3(lockPath, "wx", 384);
58799
+ lock = openSync4(lockPath, "wx", 384);
58700
58800
  } catch (error3) {
58701
58801
  if (error3 && typeof error3 === "object" && "code" in error3 && error3.code === "EEXIST") throw new McpConfigEditError("config_locked", "Another configuration edit holds the lock. Retry after it finishes; investigate stale locks before removing them.");
58702
58802
  throw error3;
58703
58803
  }
58704
- writeFileSync5(lock, JSON.stringify({ pid: process.pid }) + "\n");
58804
+ writeFileSync6(lock, JSON.stringify({ pid: process.pid }) + "\n");
58705
58805
  const before = snapshot(path);
58706
58806
  if (options.path && before && options.trustHash !== configHash(before.text)) {
58707
58807
  const sha2562 = configHash(before.text);
@@ -58715,23 +58815,23 @@ function updateMcpConfig(options, update) {
58715
58815
  const checked = parseMcpConfig(text, path);
58716
58816
  if (checked.diagnostics.some((diagnostic2) => diagnostic2.severity === "error")) throw new McpConfigEditError("invalid_server", "The server configuration is invalid. Check transport fields, URL, profile, protocol and environment/header references; no changes were saved.");
58717
58817
  temp = path + "." + randomUUID3() + ".tmp";
58718
- const fd = openSync3(temp, "wx", 384);
58818
+ const fd = openSync4(temp, "wx", 384);
58719
58819
  try {
58720
- writeFileSync5(fd, text, "utf8");
58820
+ writeFileSync6(fd, text, "utf8");
58721
58821
  fsyncSync(fd);
58722
58822
  } finally {
58723
- closeSync3(fd);
58823
+ closeSync4(fd);
58724
58824
  }
58725
58825
  if (!same(before, snapshot(path))) throw new McpConfigEditError("config_changed", "The configuration changed during this edit; no changes were saved. Review the latest file and retry.");
58726
58826
  renameSync3(temp, path);
58727
58827
  temp = void 0;
58728
58828
  let dirFd;
58729
58829
  try {
58730
- dirFd = openSync3(directory, "r");
58830
+ dirFd = openSync4(directory, "r");
58731
58831
  fsyncSync(dirFd);
58732
58832
  } catch {
58733
58833
  } finally {
58734
- if (dirFd !== void 0) closeSync3(dirFd);
58834
+ if (dirFd !== void 0) closeSync4(dirFd);
58735
58835
  }
58736
58836
  return { path, sha256: configHash(text), config: { servers: checked.servers } };
58737
58837
  } catch (error3) {
@@ -58744,12 +58844,12 @@ function updateMcpConfig(options, update) {
58744
58844
  }
58745
58845
  if (lock !== void 0) {
58746
58846
  try {
58747
- const held = fstatSync3(lock);
58847
+ const held = fstatSync4(lock);
58748
58848
  const current = lstatSync3(lockPath);
58749
58849
  if (held.dev === current.dev && held.ino === current.ino) unlinkSync(lockPath);
58750
58850
  } catch {
58751
58851
  }
58752
- closeSync3(lock);
58852
+ closeSync4(lock);
58753
58853
  }
58754
58854
  }
58755
58855
  }
@@ -59164,7 +59264,7 @@ var Chat = class {
59164
59264
  const before = chars.slice(0, m.start).join("");
59165
59265
  const after = chars.slice(m.end).join("");
59166
59266
  const trailing = item.name.endsWith("/") ? "" : " ";
59167
- const next = `${before}@${item.name}${trailing}`;
59267
+ const next = `${before}@${formatMention(item.name)}${trailing}`;
59168
59268
  this.composer.clear();
59169
59269
  this.composer.insert(next);
59170
59270
  this.composer.insert(after);
@@ -59223,7 +59323,7 @@ var Chat = class {
59223
59323
  confirmView(call, selected) {
59224
59324
  const a = call.arguments;
59225
59325
  const text = (k) => relativise(typeof a[k] === "string" ? a[k] : "", this.settings.cwd);
59226
- const preview = (s, max) => {
59326
+ const preview2 = (s, max) => {
59227
59327
  const lines2 = s.replace(/\s+$/, "").split("\n");
59228
59328
  return lines2.length > max ? [...lines2.slice(0, max), `\u2026 +${lines2.length - max} lines`] : lines2;
59229
59329
  };
@@ -59232,27 +59332,27 @@ var Chat = class {
59232
59332
  switch (call.name) {
59233
59333
  case "bash":
59234
59334
  title = "Run this command?";
59235
- lines = preview(text("command"), 8);
59335
+ lines = preview2(text("command"), 8);
59236
59336
  break;
59237
59337
  case "write":
59238
59338
  title = `Write ${text("path")}?`;
59239
- lines = preview(text("content"), 6);
59339
+ lines = preview2(text("content"), 6);
59240
59340
  break;
59241
59341
  case "apply_patch":
59242
59342
  title = "Apply this patch?";
59243
- lines = preview(text("patch"), 10);
59343
+ lines = preview2(text("patch"), 10);
59244
59344
  break;
59245
59345
  case "term":
59246
59346
  title = "Send this to the terminal?";
59247
- lines = preview(text("keystrokes"), 6);
59347
+ lines = preview2(text("keystrokes"), 6);
59248
59348
  break;
59249
59349
  case "mcp":
59250
59350
  title = `Call ${text("server")}/${text("method")}?`;
59251
- lines = preview(JSON.stringify(a.args, null, 2), 10);
59351
+ lines = preview2(JSON.stringify(a.args, null, 2), 10);
59252
59352
  break;
59253
59353
  default:
59254
59354
  title = `Run ${call.name}?`;
59255
- lines = preview(JSON.stringify(a), 4);
59355
+ lines = preview2(JSON.stringify(a), 4);
59256
59356
  }
59257
59357
  const options = ["1. Yes", this.pendingConfirm?.force ? "2. Yes, for this call (the server requires human confirmation)" : `2. Yes, and don't ask again for ${this.permissionKey(call)} this session`, "3. No, and tell the model what to do instead"];
59258
59358
  return {
@@ -59979,7 +60079,7 @@ ${output.slice(0, 8e3)}
59979
60079
  mkdirSync7(dirname9(path), { recursive: true, mode: 448 });
59980
60080
  const existing = existsSync11(path) ? readFileSync11(path, "utf8") : "";
59981
60081
  const sep6 = existing === "" || existing.endsWith("\n") ? "" : "\n";
59982
- appendFileSync2(path, `${sep6}- ${note}
60082
+ appendFileSync(path, `${sep6}- ${note}
59983
60083
  `, "utf8");
59984
60084
  this.projectNotes = readFileSync11(path, "utf8");
59985
60085
  this.screen.append({ kind: "notice", level: "info", text: `noted in ${path}; the next task reads it` });
@@ -60961,7 +61061,7 @@ function readHistory(path) {
60961
61061
  function appendHistory(path, text) {
60962
61062
  try {
60963
61063
  mkdirSync7(dirname9(path), { recursive: true, mode: 448 });
60964
- appendFileSync2(path, JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), text }) + "\n", "utf8");
61064
+ appendFileSync(path, JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), text }) + "\n", "utf8");
60965
61065
  } catch {
60966
61066
  }
60967
61067
  }
@@ -61195,8 +61295,67 @@ function saveUserSettings(updates, home = homedir7()) {
61195
61295
  return path;
61196
61296
  }
61197
61297
 
61298
+ // packages/cli/src/approval.ts
61299
+ import { createInterface } from "node:readline";
61300
+ function preview(value) {
61301
+ const text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
61302
+ const limit = 240;
61303
+ return JSON.stringify(sanitize(text.slice(0, limit))) + (text.length > limit ? "\u2026" : "");
61304
+ }
61305
+ function describe4(call) {
61306
+ const args = call.arguments;
61307
+ switch (call.name) {
61308
+ case "bash":
61309
+ return `Command ${preview(args.command)}`;
61310
+ case "write":
61311
+ return `File ${preview(args.path)}, content ${preview(args.content)}`;
61312
+ case "apply_patch":
61313
+ return `Patch ${preview(args.patch)}`;
61314
+ case "term":
61315
+ return `Terminal input ${preview(args.keystrokes)}`;
61316
+ case "mcp":
61317
+ return `MCP ${preview(args.server)} / ${preview(args.method)}, arguments ${preview(args.args)}`;
61318
+ default:
61319
+ return preview(args);
61320
+ }
61321
+ }
61322
+ function askForApproval(call, channel) {
61323
+ const { input, output, signal } = channel;
61324
+ if (signal?.aborted) return Promise.resolve("deny");
61325
+ if (!channel.interactive || !input.readable) {
61326
+ output.write(`refused ${call.name}: --permissions ask has no approval channel in this run; use --permissions auto to allow it
61327
+ `);
61328
+ return Promise.resolve("deny");
61329
+ }
61330
+ return new Promise((resolve20) => {
61331
+ const rl = createInterface({ input, output, terminal: false });
61332
+ let settled = false;
61333
+ const finish = (verdict, answered = false) => {
61334
+ if (settled) return;
61335
+ settled = true;
61336
+ signal?.removeEventListener("abort", onAbort);
61337
+ rl.close();
61338
+ if (!answered) output.write("\n");
61339
+ resolve20(verdict);
61340
+ };
61341
+ const onAbort = () => finish("deny");
61342
+ signal?.addEventListener("abort", onAbort, { once: true });
61343
+ rl.once("close", onAbort);
61344
+ rl.once("error", onAbort);
61345
+ output.write(`${describe4(call)}
61346
+ `);
61347
+ rl.question(`Allow ${call.name}? [y/N] `, (answer) => {
61348
+ if (input.readableEnded) {
61349
+ finish("deny");
61350
+ return;
61351
+ }
61352
+ finish(/^(?:y|yes)$/i.test(answer.trim()) ? "allow" : "deny", true);
61353
+ });
61354
+ });
61355
+ }
61356
+
61198
61357
  // packages/cli/src/mcp-command.ts
61199
- import { mkdirSync as mkdirSync8, readFileSync as readFileSync14, statSync as statSync8, writeFileSync as writeFileSync6 } from "node:fs";
61358
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync14, statSync as statSync8, writeFileSync as writeFileSync7 } from "node:fs";
61200
61359
  import { dirname as dirname11, resolve as resolve14 } from "node:path";
61201
61360
 
61202
61361
  // packages/cli/src/github-login.ts
@@ -61733,7 +61892,7 @@ async function runMcpCommand(rest, flags, options = {}) {
61733
61892
  written = resolve14(cwd, value("write"));
61734
61893
  try {
61735
61894
  mkdirSync8(dirname11(written), { recursive: true, mode: 448 });
61736
- writeFileSync6(written, JSON.stringify(result.config, null, 2) + "\n", { encoding: "utf8", mode: 384, flag: "wx" });
61895
+ writeFileSync7(written, JSON.stringify(result.config, null, 2) + "\n", { encoding: "utf8", mode: 384, flag: "wx" });
61737
61896
  } catch {
61738
61897
  err("Could not create the output file; existing files are never overwritten.\n");
61739
61898
  return 1;
@@ -61802,14 +61961,14 @@ import { resolve as resolve19 } from "node:path";
61802
61961
 
61803
61962
  // packages/cli/src/plugin-connections.ts
61804
61963
  import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
61805
- import { cpSync, existsSync as existsSync15, lstatSync as lstatSync5, mkdirSync as mkdirSync10, readFileSync as readFileSync16, readdirSync as readdirSync6, realpathSync as realpathSync10, renameSync as renameSync5, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "node:fs";
61964
+ import { cpSync, existsSync as existsSync15, lstatSync as lstatSync5, mkdirSync as mkdirSync10, readFileSync as readFileSync16, readdirSync as readdirSync6, realpathSync as realpathSync10, renameSync as renameSync5, rmSync as rmSync4, writeFileSync as writeFileSync9 } from "node:fs";
61806
61965
  import { homedir as homedir9 } from "node:os";
61807
61966
  import { dirname as dirname13, isAbsolute as isAbsolute8, join as join16, relative as relative7, resolve as resolve17, sep as sep5 } from "node:path";
61808
61967
 
61809
61968
  // packages/cli/src/skill-installer.ts
61810
61969
  import { createHash as createHash7 } from "node:crypto";
61811
61970
  import { execFileSync as execFileSync3 } from "node:child_process";
61812
- import { chmodSync as chmodSync2, closeSync as closeSync4, existsSync as existsSync14, lstatSync as lstatSync4, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync2, openSync as openSync4, readFileSync as readFileSync15, readdirSync as readdirSync5, realpathSync as realpathSync9, renameSync as renameSync4, rmSync as rmSync3, statSync as statSync9, writeFileSync as writeFileSync7 } from "node:fs";
61971
+ import { chmodSync as chmodSync2, closeSync as closeSync5, existsSync as existsSync14, lstatSync as lstatSync4, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync2, openSync as openSync5, readFileSync as readFileSync15, readdirSync as readdirSync5, realpathSync as realpathSync9, renameSync as renameSync4, rmSync as rmSync3, statSync as statSync9, writeFileSync as writeFileSync8 } from "node:fs";
61813
61972
  import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
61814
61973
  import { basename as basename3, dirname as dirname12, isAbsolute as isAbsolute7, join as join15, relative as relative6, resolve as resolve16, sep as sep4 } from "node:path";
61815
61974
  var MAX_METADATA = 2 * 1024 * 1024;
@@ -62302,7 +62461,7 @@ function readIndex(root) {
62302
62461
  function writeIndex(root, index) {
62303
62462
  const temp = join15(root, `.skills-index-${process.pid}-${Date.now()}.tmp`);
62304
62463
  try {
62305
- writeFileSync7(temp, JSON.stringify(index, null, 2) + "\n", { mode: 384, flag: "wx" });
62464
+ writeFileSync8(temp, JSON.stringify(index, null, 2) + "\n", { mode: 384, flag: "wx" });
62306
62465
  renameSync4(temp, indexPath(root));
62307
62466
  } finally {
62308
62467
  rmSync3(temp, { force: true });
@@ -62313,14 +62472,14 @@ function withLock(root, run) {
62313
62472
  const path = join15(root, ".skills-install.lock");
62314
62473
  let fd;
62315
62474
  try {
62316
- fd = openSync4(path, "wx", 384);
62475
+ fd = openSync5(path, "wx", 384);
62317
62476
  } catch {
62318
62477
  return fail2("install_locked", "Another skill install is in progress; retry after it completes.");
62319
62478
  }
62320
62479
  try {
62321
62480
  return run();
62322
62481
  } finally {
62323
- closeSync4(fd);
62482
+ closeSync5(fd);
62324
62483
  rmSync3(path, { force: true });
62325
62484
  }
62326
62485
  }
@@ -62442,7 +62601,7 @@ function installSkillCandidates(inspection, options = {}, replacing) {
62442
62601
  for (const file of bundle.files) {
62443
62602
  const path = join15(staging, file.path);
62444
62603
  mkdirSync9(dirname12(path), { recursive: true });
62445
- writeFileSync7(path, file.data, { flag: "wx", mode: file.mode });
62604
+ writeFileSync8(path, file.data, { flag: "wx", mode: file.mode });
62446
62605
  chmodSync2(path, file.mode);
62447
62606
  }
62448
62607
  if (tree(staging).digest !== bundle.digest) fail2("copy_changed", "Package changed during copying.");
@@ -62838,7 +62997,7 @@ async function connectInstalledSkill(name, options = {}) {
62838
62997
  const temp = `${plan.provenancePath}.${randomUUID4()}.tmp`;
62839
62998
  mkdirSync10(dirname13(temp), { recursive: true, mode: 448 });
62840
62999
  try {
62841
- writeFileSync8(temp, JSON.stringify({ version: 1, servers: provenance }, null, 2) + "\n", { mode: 384, flag: "wx" });
63000
+ writeFileSync9(temp, JSON.stringify({ version: 1, servers: provenance }, null, 2) + "\n", { mode: 384, flag: "wx" });
62842
63001
  const saved2 = updateMcpConfig({ home: config2.home, cwd: config2.cwd, path: plan.configPath, trustHash: plan.configHash }, (current) => {
62843
63002
  if ((readRegular(plan.configPath) === void 0 ? void 0 : configHash(readRegular(plan.configPath))) !== plan.configHash || (readRegular(plan.provenancePath) === void 0 ? void 0 : hash(readRegular(plan.provenancePath))) !== plan.provenanceHash) fail3("plan_changed", "Connection configuration changed; review again before connecting.");
62844
63003
  return { servers: [...current.servers.filter((row) => !selected.some((candidate2) => candidate2.id === row.id)), ...selectedConfigs] };
@@ -63286,14 +63445,14 @@ async function runPluginsArgv(argv, initialFlags = {}, options = {}) {
63286
63445
  }
63287
63446
 
63288
63447
  // packages/cli/src/plugin-connect-ui.ts
63289
- import { createInterface } from "node:readline/promises";
63448
+ import { createInterface as createInterface2 } from "node:readline/promises";
63290
63449
  function pluginConnectionUi(signal) {
63291
63450
  return {
63292
63451
  signal,
63293
63452
  confirm: async (plan) => {
63294
63453
  if (!process.stdin.isTTY || !process.stderr.isTTY || signal?.aborted) return false;
63295
63454
  process.stderr.write(JSON.stringify(plan, null, 2).replace(/[\x1b\x7f-\x9f]/g, "") + "\n");
63296
- const input = createInterface({ input: process.stdin, output: process.stderr });
63455
+ const input = createInterface2({ input: process.stdin, output: process.stderr });
63297
63456
  try {
63298
63457
  return /^(?:y|yes)$/i.test((await input.question("Register and start these reviewed connections? [y/N] ", { signal })).trim());
63299
63458
  } catch {
@@ -63307,7 +63466,7 @@ function pluginConnectionUi(signal) {
63307
63466
  }
63308
63467
 
63309
63468
  // packages/cli/src/main.ts
63310
- var VERSION = "0.5.0";
63469
+ var VERSION = "0.5.2";
63311
63470
  var SHORT_FLAGS = { p: "print", c: "continue", i: "interactive", v: "verbose", h: "help" };
63312
63471
  var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
63313
63472
  "print",
@@ -63328,6 +63487,10 @@ function parseArgs(argv) {
63328
63487
  let command = "run";
63329
63488
  for (let i = 0; i < argv.length; i++) {
63330
63489
  let a = argv[i];
63490
+ if (a === "--") {
63491
+ rest.push(...argv.slice(i + 1));
63492
+ break;
63493
+ }
63331
63494
  if (/^-[a-z]$/.test(a) && SHORT_FLAGS[a.slice(1)]) a = `--${SHORT_FLAGS[a.slice(1)]}`;
63332
63495
  if (a === "--help") {
63333
63496
  if (command === "mcp") flags.help = true;
@@ -63515,6 +63678,7 @@ var HELP = `motif ${VERSION} \u2014 a coding agent built for Motif-3 (unofficial
63515
63678
  motif open the interactive session (a terminal is required)
63516
63679
  motif "<task>" run one task and exit; add --interactive to stay
63517
63680
  motif -p "<question>" print only the final reply, for scripts and pipes (also --print)
63681
+ motif -p -- "--help" treat what follows -- as task text, not flags or subcommands
63518
63682
  motif login paste the selected provider's API key; it is checked and saved to ~/.motif/.env
63519
63683
  motif logout remove the saved key
63520
63684
  motif doctor check the endpoint, the credentials and what the server produces
@@ -64004,6 +64168,9 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64004
64168
  const activeToolNames = CORE_TOOL_NAMES.slice(0, activeTools.length);
64005
64169
  const schemaHash = toolSchemaHash(activeTools);
64006
64170
  const promptHash = systemPromptHash(systemFor(channel));
64171
+ const printSystemFor = (ch) => buildSystemPrompt({ mode: "chat", channel: ch, tools: activeTools, skills, agents, ...projectNotes !== void 0 ? { projectNotes } : {}, cwd });
64172
+ const printPromptHash = systemPromptHash(printSystemFor(channel));
64173
+ const resumePromptHash = resumeFrom?.header.prompt.systemHash === printPromptHash ? printPromptHash : promptHash;
64007
64174
  const printOnly = args.flags["print"] === true || args.flags["p"] === true;
64008
64175
  const abort = new AbortController();
64009
64176
  let stopInteractive;
@@ -64021,7 +64188,7 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64021
64188
  let task;
64022
64189
  if (resumeFrom) {
64023
64190
  const blocker = checkResumable(resumeFrom, {
64024
- systemHash: promptHash,
64191
+ systemHash: resumePromptHash,
64025
64192
  toolSchemaHash: schemaHash,
64026
64193
  model,
64027
64194
  endpoint
@@ -64150,6 +64317,66 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64150
64317
  if (key === null) return 2;
64151
64318
  sessionKey = key;
64152
64319
  }
64320
+ const runId = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-") + "-" + randomUUID5();
64321
+ const explicitJournalPath = flagStr(args.flags, "journal", "");
64322
+ const journalPath = explicitJournalPath || join18(cwd, CONFIG_DIR, "sessions", `${runId}.jsonl`);
64323
+ const journal = new Journal(
64324
+ journalPath,
64325
+ newHeader({
64326
+ runId,
64327
+ cwd,
64328
+ model,
64329
+ endpoint,
64330
+ systemHash: resumeFrom ? resumePromptHash : printOnly ? printPromptHash : promptHash,
64331
+ toolSchemaHash: schemaHash,
64332
+ harnessVersion: VERSION,
64333
+ config: {
64334
+ initialChannel: channel,
64335
+ channelPolicy,
64336
+ temperature: SAMPLING_DEFAULTS.temperature,
64337
+ topP: SAMPLING_DEFAULTS.top_p,
64338
+ ...seed !== void 0 ? { seed } : {},
64339
+ maxTurns,
64340
+ ...maxOutputTokens !== void 0 ? { maxOutputTokens } : {},
64341
+ maxRepairs: 2
64342
+ }
64343
+ }),
64344
+ // One-shot callers such as the benchmark adapter can prepare the output.
64345
+ { allowExisting: !printOnly && explicitJournalPath !== "" }
64346
+ );
64347
+ const rootScope = { scopeId: "root", scopeKind: "root" };
64348
+ journal.record(rootScope, {
64349
+ t: "scope_start",
64350
+ task,
64351
+ initialMessages: [{ role: "user", content: task }]
64352
+ });
64353
+ if (resumeFrom?.checkpoint) {
64354
+ journal.record(rootScope, {
64355
+ t: "resume",
64356
+ fromSeq: resumeFrom.checkpoint.afterSeq,
64357
+ previousRunId: resumeFrom.header.runId
64358
+ });
64359
+ }
64360
+ const rootSink = journal.sinkFor(rootScope);
64361
+ const rootCheckpoint = journal.checkpointFor(rootScope);
64362
+ const recordEnd = (result) => {
64363
+ if (result.reason === "aborted" && abort.signal.aborted) return;
64364
+ journal.record(rootScope, {
64365
+ t: "scope_end",
64366
+ result: {
64367
+ endReason: result.reason,
64368
+ ...result.summary !== void 0 ? { summary: result.summary } : {},
64369
+ turns: result.turns
64370
+ }
64371
+ });
64372
+ };
64373
+ const approvalChannel = {
64374
+ input: process.stdin,
64375
+ output: process.stderr,
64376
+ interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
64377
+ signal: abort.signal
64378
+ };
64379
+ const approval = permissions === "ask" ? (call) => askForApproval(call, approvalChannel) : void 0;
64153
64380
  if (printOnly) {
64154
64381
  const transport2 = new HttpTransport({ endpoint, model, ...sessionKey !== void 0 ? { apiKey: sessionKey } : {} });
64155
64382
  const executor2 = new ToolExecutor({
@@ -64158,23 +64385,28 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64158
64385
  skills,
64159
64386
  policy: policyForAgent({ root: cwd, tools: activeToolNames, readOnly: false }),
64160
64387
  timeoutMs: bashTimeout * 1e3,
64161
- callMcp: (server, method, values, signal, observe) => mcp.invoke(server, method, values, { scopeId: "root", signal, observe })
64388
+ callMcp: (server, method, values, signal, observe) => mcp.invoke(server, method, values, { scopeId: "root", signal, observe }),
64389
+ ...approval ? { confirm: approval } : {}
64162
64390
  });
64163
64391
  try {
64164
64392
  const result = await runLoop({
64165
64393
  transport: transport2,
64166
64394
  tools: activeTools,
64167
- system: (ch) => buildSystemPrompt({ mode: "chat", channel: ch, tools: activeTools, skills, agents, ...projectNotes !== void 0 ? { projectNotes } : {}, cwd }),
64395
+ system: printSystemFor,
64168
64396
  userTask: task,
64169
64397
  context: mcpConnected ? await mcp.prepare(discoveryTask, abort.signal) : void 0,
64170
64398
  replyRecovery: (content) => mcp.replyRecovery(content),
64171
64399
  signal: abort.signal,
64172
64400
  executor: executor2,
64173
64401
  emit: (e) => {
64402
+ if (e.type !== "stream") rootSink(e);
64174
64403
  if (e.type === "notice" && e.level === "error") process.stderr.write(`${e.text}
64175
64404
  `);
64176
64405
  },
64177
- scopeId: "root",
64406
+ onCheckpoint: (state) => {
64407
+ if (!abort.signal.aborted) rootCheckpoint(state);
64408
+ },
64409
+ scopeId: rootScope.scopeId,
64178
64410
  repo: { cwd },
64179
64411
  channel,
64180
64412
  channelPolicy,
@@ -64185,6 +64417,7 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64185
64417
  replyEnds: true,
64186
64418
  confirmDone: false
64187
64419
  });
64420
+ recordEnd(result);
64188
64421
  if (result.summary) process.stdout.write(result.summary.replace(/\s+$/, "") + "\n");
64189
64422
  if (result.reason !== "done") process.stderr.write(`ended: ${result.reason}
64190
64423
  `);
@@ -64195,48 +64428,19 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64195
64428
  }
64196
64429
  const transport = new HttpTransport({ endpoint, model, ...sessionKey !== void 0 ? { apiKey: sessionKey } : {} });
64197
64430
  const screen = new Screen({ showThinking, verbose: args.flags["verbose"] === true || stored.values.verbose === true, cwd });
64198
- const runId = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
64199
- const journalPath = flagStr(args.flags, "journal", "") || join18(cwd, CONFIG_DIR, "sessions", `${runId}.jsonl`);
64200
- const journal = new Journal(
64201
- journalPath,
64202
- newHeader({
64203
- runId,
64204
- cwd,
64205
- model,
64206
- endpoint,
64207
- systemHash: promptHash,
64208
- toolSchemaHash: schemaHash,
64209
- harnessVersion: VERSION,
64210
- config: {
64211
- initialChannel: channel,
64212
- channelPolicy,
64213
- temperature: SAMPLING_DEFAULTS.temperature,
64214
- topP: SAMPLING_DEFAULTS.top_p,
64215
- ...seed !== void 0 ? { seed } : {},
64216
- maxTurns,
64217
- ...maxOutputTokens !== void 0 ? { maxOutputTokens } : {},
64218
- maxRepairs: 2
64219
- }
64220
- })
64221
- );
64222
- const rootScope = { scopeId: "root", scopeKind: "root" };
64223
- journal.record(rootScope, {
64224
- t: "scope_start",
64225
- task,
64226
- initialMessages: [{ role: "user", content: task }]
64227
- });
64228
- if (resumeFrom?.checkpoint) {
64229
- journal.record(rootScope, {
64230
- t: "resume",
64231
- fromSeq: resumeFrom.checkpoint.afterSeq,
64232
- previousRunId: resumeFrom.header.runId
64233
- });
64234
- }
64235
64431
  if (args.flags["no-hero"] !== true) {
64236
64432
  screen.splash({ model, endpoint, channel, maxTokens: 262144 });
64237
64433
  }
64238
64434
  screen.attachInput(process.stdin, void 0, stop);
64239
- const rootSink = journal.sinkFor(rootScope);
64435
+ const oneShotApproval = approval && (async (call) => {
64436
+ if (!approvalChannel.interactive || !screen.interactiveInput) return approval(call);
64437
+ screen.suspendInput();
64438
+ try {
64439
+ return await approval(call);
64440
+ } finally {
64441
+ if (!abort.signal.aborted && process.stdin.readable) screen.attachInput(process.stdin, void 0, stop);
64442
+ }
64443
+ });
64240
64444
  const emit = (e) => {
64241
64445
  if (e.type !== "stream") rootSink(e);
64242
64446
  screen.apply(e);
@@ -64252,6 +64456,7 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64252
64456
  policy: policyForAgent({ root: cwd, tools: activeToolNames, readOnly: false }),
64253
64457
  timeoutMs: bashTimeout * 1e3,
64254
64458
  callMcp: (server, method, values, signal, observe) => mcp.invoke(server, method, values, { scopeId: "root", signal, observe }),
64459
+ ...oneShotApproval ? { confirm: oneShotApproval } : {},
64255
64460
  onHook: (event, label3, ok2) => emit({ type: "hook", event, label: label3, ok: ok2 }),
64256
64461
  runAgent: async (name, prompt) => {
64257
64462
  const def = agents.get(name);
@@ -64275,6 +64480,7 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64275
64480
  skills,
64276
64481
  timeoutMs: bashTimeout * 1e3,
64277
64482
  callMcp: (server, method, values, signal, observe) => mcp.invoke(server, method, values, { scopeId: childScope.scopeId, signal, observe }),
64483
+ ...oneShotApproval ? { confirm: oneShotApproval } : {},
64278
64484
  policy: policyForAgent({
64279
64485
  root: cwd,
64280
64486
  tools: CORE_TOOL_NAMES.slice(0, def.toolCount),
@@ -64342,7 +64548,6 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64342
64548
  }, (out) => !out.ok);
64343
64549
  }
64344
64550
  });
64345
- const rootCheckpoint = journal.checkpointFor(rootScope);
64346
64551
  try {
64347
64552
  const result = await runLoop({
64348
64553
  transport,
@@ -64377,14 +64582,7 @@ user file ${stored.userPath}${existsSync17(stored.userPath) ? "" : " (absent
64377
64582
  // and the screen ignores them there.
64378
64583
  stream: Boolean(process.stdout.isTTY)
64379
64584
  });
64380
- if (!(result.reason === "aborted" && abort.signal.aborted)) journal.record(rootScope, {
64381
- t: "scope_end",
64382
- result: {
64383
- endReason: result.reason,
64384
- ...result.summary !== void 0 ? { summary: result.summary } : {},
64385
- turns: result.turns
64386
- }
64387
- });
64585
+ recordEnd(result);
64388
64586
  return result.reason === "done" ? 0 : 1;
64389
64587
  } finally {
64390
64588
  executor.close();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "motifcode",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "type": "module",
5
5
  "description": "Unofficial coding agent harness built for Motif-3: a Claude Code-style terminal session over the hosted endpoint",
6
6
  "keywords": [