@vibest/cli 0.0.1-beta.18 → 0.0.1-beta.20

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.
@@ -3121,6 +3121,9 @@ function isNever(_) {
3121
3121
  function isUnknown(_) {
3122
3122
  return true;
3123
3123
  }
3124
+ function isObjectOrArray(input) {
3125
+ return typeof input === "object" && input !== null;
3126
+ }
3124
3127
  function isObject(input) {
3125
3128
  return typeof input === "object" && input !== null && !Array.isArray(input);
3126
3129
  }
@@ -4285,6 +4288,7 @@ var Number2 = /* @__PURE__ */ make((self, that) => {
4285
4288
  });
4286
4289
  var mapInput = /* @__PURE__ */ dual(2, (self, f) => make((b1, b2) => self(f(b1), f(b2))));
4287
4290
  var isGreaterThan = (O) => dual(2, (self, that) => O(self, that) === 1);
4291
+ var isGreaterThanOrEqualTo = (O) => dual(2, (self, that) => O(self, that) !== -1);
4288
4292
  var min = (O) => dual(2, (self, that) => self === that || O(self, that) < 1 ? self : that);
4289
4293
 
4290
4294
  // ../../../node_modules/.pnpm/effect@4.0.2/node_modules/effect/dist/Option.js
@@ -4901,6 +4905,23 @@ var Equivalence = (self, that) => matchPair(self, that, {
4901
4905
  onInfinity: (self, that) => self.value._tag === that.value._tag
4902
4906
  });
4903
4907
  var min2 = /* @__PURE__ */ min(Order);
4908
+ var sum = /* @__PURE__ */ dual(2, (self, that) => matchPair(self, that, {
4909
+ onMillis: (self, that) => make3(self + that),
4910
+ onNanos: (self, that) => make3(self + that),
4911
+ onInfinity: (self, that) => {
4912
+ const s = self.value._tag;
4913
+ const t = that.value._tag;
4914
+ if (s === "Infinity" && t === "NegativeInfinity")
4915
+ return zero;
4916
+ if (s === "NegativeInfinity" && t === "Infinity")
4917
+ return zero;
4918
+ if (s === "Infinity" || t === "Infinity")
4919
+ return infinity;
4920
+ if (s === "NegativeInfinity" || t === "NegativeInfinity")
4921
+ return negativeInfinity;
4922
+ return zero;
4923
+ }
4924
+ }));
4904
4925
  var equals2 = /* @__PURE__ */ dual(2, (self, that) => Equivalence(self, that));
4905
4926
  var parts = (self) => {
4906
4927
  if (self.value._tag === "Infinity") {
@@ -5117,6 +5138,30 @@ var Class2 = class extends Class {
5117
5138
  }
5118
5139
  }
5119
5140
  };
5141
+ var taggedEnum = () => new Proxy({}, {
5142
+ get(_target, tag, _receiver) {
5143
+ if (tag === "$is") {
5144
+ return isTagged;
5145
+ } else if (tag === "$match") {
5146
+ return taggedMatch;
5147
+ }
5148
+ return (props) => ({
5149
+ ...props,
5150
+ _tag: tag
5151
+ });
5152
+ }
5153
+ });
5154
+ function taggedMatch() {
5155
+ if (arguments.length === 1) {
5156
+ const cases = arguments[0];
5157
+ return function(value) {
5158
+ return cases[value._tag](value);
5159
+ };
5160
+ }
5161
+ const value = arguments[0];
5162
+ const cases = arguments[1];
5163
+ return cases[value._tag](value);
5164
+ }
5120
5165
  var Error3 = Error2;
5121
5166
  var TaggedError2 = TaggedError;
5122
5167
 
@@ -7923,6 +7968,7 @@ var buildFromOptions = (options) => {
7923
7968
 
7924
7969
  // ../../../node_modules/.pnpm/effect@4.0.2/node_modules/effect/dist/Effect.js
7925
7970
  var isEffect2 = isEffect;
7971
+ var all2 = all;
7926
7972
  var forEach2 = forEach;
7927
7973
  var whileLoop2 = whileLoop;
7928
7974
  var tryPromise2 = tryPromise;
@@ -8000,6 +8046,7 @@ var runSyncExit2 = runSyncExit;
8000
8046
  var fnUntraced2 = fnUntraced;
8001
8047
  var fn2 = fn;
8002
8048
  var logError = /* @__PURE__ */ logWithLevel("Error");
8049
+ var logDebug = /* @__PURE__ */ logWithLevel("Debug");
8003
8050
  var annotateLogs = /* @__PURE__ */ dual((args) => isEffect2(args[0]), (effect, ...args) => updateService(effect, CurrentLogAnnotations2, (annotations) => {
8004
8051
  const newAnnotations = args.length === 1 ? {
8005
8052
  ...annotations,
@@ -13539,6 +13586,9 @@ function decodeUnknownEffect(schema, options) {
13539
13586
  const parser = run2(schema.ast);
13540
13587
  return options === undefined ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));
13541
13588
  }
13589
+ function decodeUnknownOption(schema, options) {
13590
+ return asOption(decodeUnknownEffect(schema, options));
13591
+ }
13542
13592
  function encodeUnknownEffect(schema, options) {
13543
13593
  const parser = run2(flip2(schema.ast));
13544
13594
  return options === undefined ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));
@@ -13581,6 +13631,17 @@ function runWithCompiler(compiler, ast) {
13581
13631
  function asExit(parser) {
13582
13632
  return (input, options) => runSyncExit2(parser(input, options));
13583
13633
  }
13634
+ function asOption(parser) {
13635
+ const parserExit = asExit(parser);
13636
+ return (input, options) => {
13637
+ const exit = parserExit(input, options);
13638
+ if (isSuccess3(exit)) {
13639
+ return some2(exit.value);
13640
+ }
13641
+ getSchemaIssueOrThrow(exit.cause, "Option adapter can only return none for schema issues");
13642
+ return none2();
13643
+ };
13644
+ }
13584
13645
  function runSync2(effect, message) {
13585
13646
  const exit = runSyncExit2(effect);
13586
13647
  if (isSuccess3(exit)) {
@@ -13948,6 +14009,7 @@ function decodeUnknownEffect2(schema, options) {
13948
14009
  return fromIssueEffect(parser(input, options));
13949
14010
  };
13950
14011
  }
14012
+ var decodeUnknownOption2 = decodeUnknownOption;
13951
14013
  function decodeUnknownSync(schema, options) {
13952
14014
  const parser = decodeUnknownEffect2(schema, options);
13953
14015
  return (input, options) => {
@@ -13973,6 +14035,9 @@ var make19 = make18;
13973
14035
  function isSchema(u) {
13974
14036
  return hasProperty(u, TypeId24) && u[TypeId24] === TypeId24;
13975
14037
  }
14038
+ var optionalKey2 = /* @__PURE__ */ lambda((schema) => make19(optionalKey(schema.ast), {
14039
+ schema
14040
+ }));
13976
14041
  var optional2 = /* @__PURE__ */ lambda((self) => {
13977
14042
  const schema = UndefinedOr(self);
13978
14043
  return make19(optional(self.ast), {
@@ -14065,12 +14130,6 @@ function Literals(literals) {
14065
14130
  }
14066
14131
  var NullOr = /* @__PURE__ */ lambda((self) => Union2([self, Null2]));
14067
14132
  var UndefinedOr = /* @__PURE__ */ lambda((self) => Union2([self, Undefined2]));
14068
- function brand(identifier) {
14069
- return (schema) => make19(schema.ast, {
14070
- schema,
14071
- identifier
14072
- });
14073
- }
14074
14133
  function decodeTo2(to, transformation) {
14075
14134
  return (from) => {
14076
14135
  return make19(decodeTo(from.ast, to.ast, transformation ? makeTransformation(transformation) : passthrough3()), {
@@ -14117,6 +14176,32 @@ function isPattern2(regExp, annotations) {
14117
14176
  ...annotations
14118
14177
  });
14119
14178
  }
14179
+ var getUUIDRegExp = (version) => {
14180
+ if (version) {
14181
+ return new globalThis.RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
14182
+ }
14183
+ return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$/;
14184
+ };
14185
+ function isUUID(version, annotations) {
14186
+ const regExp = getUUIDRegExp(version);
14187
+ return isPattern2(regExp, {
14188
+ expected: version ? `a UUID v${version}` : "a UUID",
14189
+ representation: {
14190
+ id: "effect/schema/isUUID",
14191
+ payload: {
14192
+ version: version ?? null
14193
+ }
14194
+ },
14195
+ toJsonSchema: () => ({
14196
+ pattern: regExp.source,
14197
+ format: "uuid"
14198
+ }),
14199
+ toCode: () => ({
14200
+ runtime: version === undefined ? "Schema.isUUID()" : `Schema.isUUID(${version})`
14201
+ }),
14202
+ ...annotations
14203
+ });
14204
+ }
14120
14205
  function isBase64(annotations) {
14121
14206
  const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
14122
14207
  return isPattern2(regExp, {
@@ -14135,6 +14220,77 @@ function isBase64(annotations) {
14135
14220
  });
14136
14221
  }
14137
14222
  var Finite = /* @__PURE__ */ make19(finite);
14223
+ function makeIsGreaterThan(options) {
14224
+ const gt = isGreaterThan(options.order);
14225
+ const formatter = options.formatter ?? format;
14226
+ return (exclusiveMinimum, annotations) => {
14227
+ return makeFilter2((input) => gt(input, exclusiveMinimum), {
14228
+ expected: `a value greater than ${formatter(exclusiveMinimum)}`,
14229
+ arbitraryConstraint: {
14230
+ order: options.order,
14231
+ minimum: exclusiveMinimum,
14232
+ exclusiveMinimum: true
14233
+ },
14234
+ ...options.annotate?.(exclusiveMinimum),
14235
+ ...annotations
14236
+ });
14237
+ };
14238
+ }
14239
+ function makeIsGreaterThanOrEqualTo(options) {
14240
+ const gte = isGreaterThanOrEqualTo(options.order);
14241
+ const formatter = options.formatter ?? format;
14242
+ return (minimum, annotations) => {
14243
+ return makeFilter2((input) => gte(input, minimum), {
14244
+ expected: `a value greater than or equal to ${formatter(minimum)}`,
14245
+ arbitraryConstraint: {
14246
+ order: options.order,
14247
+ minimum
14248
+ },
14249
+ ...options.annotate?.(minimum),
14250
+ ...annotations
14251
+ });
14252
+ };
14253
+ }
14254
+ function encodeNumberPayload(number) {
14255
+ if (!globalThis.Number.isFinite(number)) {
14256
+ throw new globalThis.RangeError(`Expected a finite number, got ${format(number)}`);
14257
+ }
14258
+ return number;
14259
+ }
14260
+ var isGreaterThan2 = /* @__PURE__ */ makeIsGreaterThan({
14261
+ order: Number2,
14262
+ annotate: (exclusiveMinimum) => ({
14263
+ representation: {
14264
+ id: "effect/schema/isGreaterThan",
14265
+ payload: {
14266
+ exclusiveMinimum: encodeNumberPayload(exclusiveMinimum)
14267
+ }
14268
+ },
14269
+ toJsonSchema: () => ({
14270
+ exclusiveMinimum
14271
+ }),
14272
+ toCode: () => ({
14273
+ runtime: `Schema.isGreaterThan(${format(exclusiveMinimum)})`
14274
+ })
14275
+ })
14276
+ });
14277
+ var isGreaterThanOrEqualTo2 = /* @__PURE__ */ makeIsGreaterThanOrEqualTo({
14278
+ order: Number2,
14279
+ annotate: (minimum) => ({
14280
+ representation: {
14281
+ id: "effect/schema/isGreaterThanOrEqualTo",
14282
+ payload: {
14283
+ minimum: encodeNumberPayload(minimum)
14284
+ }
14285
+ },
14286
+ toJsonSchema: () => ({
14287
+ minimum
14288
+ }),
14289
+ toCode: () => ({
14290
+ runtime: `Schema.isGreaterThanOrEqualTo(${format(minimum)})`
14291
+ })
14292
+ })
14293
+ });
14138
14294
  function isInt(annotations) {
14139
14295
  return makeFilter2((n) => globalThis.Number.isSafeInteger(n), {
14140
14296
  expected: "an integer",
@@ -14155,6 +14311,41 @@ function isInt(annotations) {
14155
14311
  });
14156
14312
  }
14157
14313
  var Int = /* @__PURE__ */ Number5.check(/* @__PURE__ */ isInt());
14314
+ function makeIsMinLength(minLength, minCodePoints, annotations) {
14315
+ return makeFilter2((input) => input.length >= minLength, {
14316
+ expected: `a value with a length of at least ${minLength}`,
14317
+ representation: {
14318
+ id: "effect/schema/isMinLength",
14319
+ payload: {
14320
+ minLength
14321
+ }
14322
+ },
14323
+ toJsonSchema: ({
14324
+ type
14325
+ }) => type === "string" ? minLength <= 1 ? {
14326
+ minLength: minCodePoints
14327
+ } : [{
14328
+ minLength: minCodePoints
14329
+ }, true] : type === "array" ? {
14330
+ minItems: minLength
14331
+ } : type === undefined ? [{
14332
+ minLength: minCodePoints,
14333
+ minItems: minLength
14334
+ }, true] : [{}, true],
14335
+ toCode: () => ({
14336
+ runtime: `Schema.isMinLength(${minLength})`
14337
+ }),
14338
+ [STRUCTURAL_ANNOTATION_KEY]: true,
14339
+ arbitraryConstraint: {
14340
+ minLength
14341
+ },
14342
+ ...annotations
14343
+ });
14344
+ }
14345
+ function isNonEmpty(annotations) {
14346
+ return makeIsMinLength(1, 1, annotations);
14347
+ }
14348
+ var NonEmptyString = /* @__PURE__ */ String4.check(/* @__PURE__ */ isNonEmpty());
14158
14349
  var getErrorOptionsKey = (options) => (options?.includeStack === true ? 1 : 0) | (options?.excludeCause === true ? 2 : 0);
14159
14350
  var getErrorOptions = (key) => {
14160
14351
  switch (key) {
@@ -14353,6 +14544,7 @@ var Uint8Array2 = /* @__PURE__ */ instanceOf(globalThis.Uint8Array, {
14353
14544
  expected: "Uint8Array",
14354
14545
  toCodecJson: () => link3()(Base64String, uint8ArrayFromBase64String)
14355
14546
  });
14547
+ var Uint8ArrayFromBase64 = /* @__PURE__ */ Base64String.pipe(/* @__PURE__ */ decodeTo2(Uint8Array2, uint8ArrayFromBase64String));
14356
14548
  function CauseReason(error, defect) {
14357
14549
  const schema = declareConstructor()([error, defect], ([error, defect]) => (input, ast, options) => {
14358
14550
  if (!isReason(input)) {
@@ -15139,8 +15331,10 @@ var fromDuplex = (open, options) => withFiber2((fiber) => {
15139
15331
  }));
15140
15332
  });
15141
15333
 
15334
+ // ../../schema/src/version.ts
15335
+ var PROTOCOL = 11;
15336
+
15142
15337
  // ../../protocol/src/protocol.ts
15143
- var PROTOCOL = 8;
15144
15338
  var MISMATCH_ACTION = "vibest update";
15145
15339
  var protocolMismatch = (caller, server, version, callerVersion) => ({
15146
15340
  protocol: server,
@@ -15154,32 +15348,27 @@ var SESSION_HEADER = "vibest-session-id";
15154
15348
  var REPOSITORY_HEADER = "vibest-repository";
15155
15349
  var PROJECT_HEADER = "vibest-project-id";
15156
15350
  var HARNESS_SESSION_HEADER = "vibest-harness-session-id";
15157
- var AGENT_HEADER = "vibest-agent";
15158
15351
  var HARNESS_HEADER = "vibest-harness";
15159
15352
  var CWD_HEADER = "vibest-cwd";
15160
15353
  var RUNTIME_HEADER = "vibest-runtime";
15161
15354
  var PLUGIN_VERSION_HEADER = "vibest-plugin-version";
15162
- var sessionHeaders = (who) => {
15163
- const headers = {
15164
- [PROTOCOL_HEADER]: String(PROTOCOL),
15165
- [CALLER_HEADER]: "session",
15166
- [SESSION_HEADER]: who.sessionId
15167
- };
15168
- const put = (name, value) => {
15169
- if (value)
15170
- headers[name] = value;
15171
- };
15172
- put(PROJECT_HEADER, who.projectId);
15173
- put(HARNESS_SESSION_HEADER, who.harnessSessionId);
15174
- put(AGENT_HEADER, who.agent);
15175
- put(HARNESS_HEADER, who.harness);
15176
- put(CWD_HEADER, who.cwd === undefined ? undefined : encodeURIComponent(who.cwd));
15177
- put(RUNTIME_HEADER, who.runtime);
15178
- put(PLUGIN_VERSION_HEADER, who.pluginVersion);
15179
- if (who.repositoryRoot !== undefined)
15180
- headers[REPOSITORY_HEADER] = who.repositoryRoot;
15181
- return headers;
15182
- };
15355
+ var PROCESS_HEADER = "vibest-process";
15356
+ var presentHeaders = (headers) => Object.fromEntries(headers.flatMap(([name, value]) => value ? [[name, value]] : []));
15357
+ var sessionHeaders = (who) => ({
15358
+ [PROTOCOL_HEADER]: String(PROTOCOL),
15359
+ [CALLER_HEADER]: "session",
15360
+ [SESSION_HEADER]: who.sessionId,
15361
+ ...presentHeaders([
15362
+ [PROJECT_HEADER, who.projectId],
15363
+ [HARNESS_SESSION_HEADER, who.harnessSessionId],
15364
+ [HARNESS_HEADER, who.harness],
15365
+ [CWD_HEADER, who.cwd === undefined ? undefined : encodeURIComponent(who.cwd)],
15366
+ [RUNTIME_HEADER, who.runtime],
15367
+ [PLUGIN_VERSION_HEADER, who.pluginVersion],
15368
+ [PROCESS_HEADER, who.process]
15369
+ ]),
15370
+ ...who.repositoryRoot !== undefined && { [REPOSITORY_HEADER]: who.repositoryRoot }
15371
+ });
15183
15372
  // ../../../node_modules/.pnpm/effect@4.0.2/node_modules/effect/dist/ConfigProvider.js
15184
15373
  function makeValue(value) {
15185
15374
  return {
@@ -15568,6 +15757,9 @@ var makeUnsafe6 = (value) => {
15568
15757
  var make24 = (value) => sync2(() => makeUnsafe6(value));
15569
15758
  var get2 = (self) => sync2(() => self.ref.current);
15570
15759
  var set2 = /* @__PURE__ */ dual(2, (self, value) => sync2(() => set(self.ref, value)));
15760
+ // ../../schema/src/id.ts
15761
+ var RequestId = String4.check(isUUID(4));
15762
+
15571
15763
  // ../../schema/src/machine.ts
15572
15764
  class MachineFailed extends TaggedError3()("MachineFailed", { message: String4 }) {
15573
15765
  }
@@ -15657,63 +15849,13 @@ var OutboxItem = Struct({
15657
15849
  id: String4,
15658
15850
  session: String4,
15659
15851
  recipient: String4,
15660
- kind: Literals(["result", "notice"]),
15852
+ kind: Literals(["send", "notice"]),
15661
15853
  content: String4,
15662
15854
  cut: optional2(Boolean3)
15663
15855
  });
15664
15856
 
15665
- // ../../schema/src/id.ts
15666
- var ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
15667
-
15668
15857
  // ../../schema/src/model.ts
15669
- var ProjectID = brand("ProjectID")(String4.check(isPattern2(ID)));
15670
- var SessionID = brand("SessionID")(String4.check(isPattern2(ID)));
15671
- var InboxID = brand("InboxID")(Int);
15672
- var MessageID = brand("MessageID")(Int);
15673
- var Time = Number5;
15674
- var Json3 = Record(String4, Unknown2);
15675
- var Project = Struct({
15676
- id: ProjectID,
15677
- directory: String4,
15678
- mainSessionId: optional2(SessionID)
15679
- });
15680
- var Runtime = Json3;
15681
- var Session = Struct({
15682
- id: SessionID,
15683
- projectId: ProjectID,
15684
- parentSessionId: optional2(SessionID),
15685
- agentType: String4,
15686
- harness: String4,
15687
- directory: String4,
15688
- runtime: optional2(Runtime),
15689
- harnessSessionId: optional2(String4),
15690
- metadata: Json3,
15691
- createdAt: Time,
15692
- endedAt: optional2(Time)
15693
- });
15694
- var SenderType = Literals(["user", "session", "system", "plugin"]);
15695
- var DeliveryStatus = Literals(["pending", "delivering", "delivered", "failed", "dropped"]);
15696
- var Inbox = Struct({
15697
- id: InboxID,
15698
- recipientSessionId: SessionID,
15699
- senderType: SenderType,
15700
- senderId: optional2(String4),
15701
- content: String4,
15702
- resultMessageId: optional2(MessageID),
15703
- deliveryStatus: DeliveryStatus
15704
- });
15705
15858
  var MessageStatus = Literals(["working", "completed", "failed", "interrupted", "lost", "not_started"]);
15706
- var Message = Struct({
15707
- id: MessageID,
15708
- sessionId: SessionID,
15709
- inboxId: optional2(InboxID),
15710
- input: String4,
15711
- output: optional2(String4),
15712
- status: MessageStatus,
15713
- metadata: Json3,
15714
- startedAt: Time,
15715
- endedAt: optional2(Time)
15716
- });
15717
15859
 
15718
15860
  // ../../schema/src/plugin.ts
15719
15861
  class AgentRefused extends TaggedError3()("AgentRefused", {
@@ -15727,6 +15869,14 @@ class AgentRefused extends TaggedError3()("AgentRefused", {
15727
15869
 
15728
15870
  class HookFailed extends TaggedError3()("HookFailed", { message: String4 }) {
15729
15871
  }
15872
+
15873
+ class PluginsNotActive extends TaggedError3()("PluginsNotActive", {
15874
+ plugins: ArraySchema(String4)
15875
+ }) {
15876
+ get message() {
15877
+ return this.plugins.length === 0 ? "plugins still loading" : `plugins still loading: ${this.plugins.join(", ")}`;
15878
+ }
15879
+ }
15730
15880
  var Change = Struct({
15731
15881
  field: String4,
15732
15882
  from: optional2(Unknown2),
@@ -15771,6 +15921,12 @@ var ProjectInfoResult = Struct({
15771
15921
  artifacts: String4
15772
15922
  });
15773
15923
  var ProjectSearchInput = Struct({ query: String4, kind: optional2(ProjectKind) });
15924
+ var ProjectActivity = Literals(["blocked", "done", "working", "idle"]);
15925
+
15926
+ class ProjectCreateFailed extends TaggedError3()("ProjectCreateFailed", {
15927
+ message: String4
15928
+ }) {
15929
+ }
15774
15930
 
15775
15931
  // ../../schema/src/remove.ts
15776
15932
  var RemoveOutcome = Struct({
@@ -15784,11 +15940,151 @@ var RemoveOutcome = Struct({
15784
15940
  reasons: ArraySchema(String4)
15785
15941
  });
15786
15942
 
15943
+ // ../../schema/src/event.ts
15944
+ var fact = (type, aggregate, fields) => ({ type, aggregate, data: Struct(fields) });
15945
+ var Text = NonEmptyString;
15946
+ var optional3 = (schema) => optionalKey2(schema);
15947
+ var Seq = Int.check(isGreaterThan2(0));
15948
+ var Pid = Int.check(isGreaterThan2(0));
15949
+ var Repository = Struct({ path: Text, remote: optional3(Text) });
15950
+ var Repositories = ArraySchema(Repository);
15951
+ var ProjectCreated = fact("project.created", "project", {
15952
+ directory: optional3(Text),
15953
+ repositories: Repositories
15954
+ });
15955
+ var ProjectMoved = fact("project.moved", "project", { from: Text, to: Text, repositories: Repositories });
15956
+ var ProjectRepositoriesChanged = fact("project.repositories_changed", "project", {
15957
+ repositories: Repositories
15958
+ });
15959
+ var ProjectEntryChanged = fact("project.entry_changed", "project", { session: optional3(Text) });
15960
+ var SessionCreated = fact("session.created", "session", {
15961
+ project: Text,
15962
+ agent: Text,
15963
+ name: Text,
15964
+ directory: String4,
15965
+ parent: optional3(Text),
15966
+ origin: optional3(Struct({ peer: Text, project: Text, session: optional3(Text) }))
15967
+ });
15968
+ var SessionRenamed = fact("session.renamed", "session", { name: Text });
15969
+ var SessionDirectoryChanged = fact("session.directory_changed", "session", { directory: Text });
15970
+ var SessionEnded = fact("session.ended", "session", { reason: Literals(["archived", "replaced"]) });
15971
+ var ProcessStarted = fact("process.started", "session", {
15972
+ harness: Text,
15973
+ provider: optional3(Text),
15974
+ model: optional3(Text),
15975
+ routing: optional3(Routing),
15976
+ resume: optional3(Text),
15977
+ runtime: Text,
15978
+ terminal: optional3(Text),
15979
+ pid: optional3(Pid)
15980
+ });
15981
+ var ProcessPlaced = fact("process.placed", "session", { process: Seq, terminal: Text, pid: optional3(Pid) });
15982
+ var ProcessReady = fact("process.ready", "session", {
15983
+ process: Seq,
15984
+ pid: optional3(Pid),
15985
+ integration: optional3(Struct({ version: Text, protocol: Int }))
15986
+ });
15987
+ var ProcessPid = fact("process.pid", "session", { process: Seq, pid: Pid });
15988
+ var ProcessConversation = fact("process.conversation", "session", { process: Seq, conversation: Text });
15989
+ var ProcessEndReason = Literals([
15990
+ "exited",
15991
+ "limited",
15992
+ "restart",
15993
+ "move",
15994
+ "archived",
15995
+ "launch_failed",
15996
+ "superseded"
15997
+ ]);
15998
+ var ProcessEnded = fact("process.ended", "session", { process: Seq, reason: ProcessEndReason });
15999
+ var ExecutionStarted = fact("execution.started", "session", {
16000
+ process: optional3(Seq),
16001
+ typed: optional3(Text)
16002
+ });
16003
+ var ExecutionAccepted = fact("execution.accepted", "session", { execution: Seq });
16004
+ var ExecutionOutcome = Literals(["completed", "failed", "interrupted", "lost", "not_started"]);
16005
+ var ExecutionEnded = fact("execution.ended", "session", {
16006
+ execution: Seq,
16007
+ outcome: ExecutionOutcome,
16008
+ failure: optional3(Struct({ message: Text, kind: optional3(Literal2("limit")) })),
16009
+ conversation: optional3(Text),
16010
+ reply: optional3(String4)
16011
+ });
16012
+ var InboxKind = Literals(["task", "send", "notice"]);
16013
+ var InboxQueued = fact("inbox.queued", "session", {
16014
+ kind: InboxKind,
16015
+ recipient: optional3(Text),
16016
+ sender: optional3(Text),
16017
+ content: String4,
16018
+ status: Literals(["pending", "delivered", "dropped"]),
16019
+ request: optional3(Text),
16020
+ peerItem: optional3(Text)
16021
+ });
16022
+ var InboxMoved = fact("inbox.moved", "session", {
16023
+ inbox: Seq,
16024
+ to: Literals(["pending", "delivering", "delivered", "failed", "dropped"]),
16025
+ execution: optional3(Seq)
16026
+ });
16027
+ var MachineAdded = fact("machine.added", "ledger", { name: Text, target: Text, vibestd: Text });
16028
+ var MachineConnected = fact("machine.connected", "ledger", { name: Text });
16029
+ var MachineRemoved = fact("machine.removed", "ledger", { name: Text });
16030
+ var PeerSeen = fact("peer.seen", "ledger", { id: Text, name: Text });
16031
+ var OutboxQueued = fact("outbox.queued", "ledger", {
16032
+ id: Text,
16033
+ peer: Text,
16034
+ session: Text,
16035
+ recipient: optional3(Text),
16036
+ kind: optional3(Literals(["send", "notice"])),
16037
+ content: String4
16038
+ });
16039
+ var OutboxAcked = fact("outbox.acked", "ledger", { peer: Text, ids: NonEmptyArray(Text) });
16040
+ var Catalog = {
16041
+ [ProjectCreated.type]: ProjectCreated,
16042
+ [ProjectMoved.type]: ProjectMoved,
16043
+ [ProjectRepositoriesChanged.type]: ProjectRepositoriesChanged,
16044
+ [ProjectEntryChanged.type]: ProjectEntryChanged,
16045
+ [SessionCreated.type]: SessionCreated,
16046
+ [SessionRenamed.type]: SessionRenamed,
16047
+ [SessionDirectoryChanged.type]: SessionDirectoryChanged,
16048
+ [SessionEnded.type]: SessionEnded,
16049
+ [ProcessStarted.type]: ProcessStarted,
16050
+ [ProcessPlaced.type]: ProcessPlaced,
16051
+ [ProcessReady.type]: ProcessReady,
16052
+ [ProcessPid.type]: ProcessPid,
16053
+ [ProcessConversation.type]: ProcessConversation,
16054
+ [ProcessEnded.type]: ProcessEnded,
16055
+ [ExecutionStarted.type]: ExecutionStarted,
16056
+ [ExecutionAccepted.type]: ExecutionAccepted,
16057
+ [ExecutionEnded.type]: ExecutionEnded,
16058
+ [InboxQueued.type]: InboxQueued,
16059
+ [InboxMoved.type]: InboxMoved,
16060
+ [MachineAdded.type]: MachineAdded,
16061
+ [MachineConnected.type]: MachineConnected,
16062
+ [MachineRemoved.type]: MachineRemoved,
16063
+ [PeerSeen.type]: PeerSeen,
16064
+ [OutboxQueued.type]: OutboxQueued,
16065
+ [OutboxAcked.type]: OutboxAcked
16066
+ };
16067
+ var byType = new Map(Object.values(Catalog).map((d) => [d.type, d]));
16068
+ class UnknownFact extends TaggedError3()("UnknownFact", {
16069
+ aggregate: String4,
16070
+ seq: Number5,
16071
+ type: String4,
16072
+ message: String4
16073
+ }) {
16074
+ }
16075
+
15787
16076
  // ../../schema/src/session.ts
15788
16077
  var AgentStatus = Literals(["idle", "working", "blocked", "done", "unknown"]);
15789
- var TurnState = Literals(["none", "open", "completed", "failed", "interrupted", "lost", "not_started"]);
15790
- var InboxKind = Literals(["send", "report", "result", "notice"]);
15791
- var InboxStatus = Literals(["pending", "sending", "delivered", "failed", "dropped"]);
16078
+ var ExecutionState = Literals([
16079
+ "none",
16080
+ "open",
16081
+ "completed",
16082
+ "failed",
16083
+ "interrupted",
16084
+ "lost",
16085
+ "not_started"
16086
+ ]);
16087
+ var InboxStatus = Literals(["pending", "delivering", "delivered", "failed", "dropped"]);
15792
16088
  var RuntimeAddress = Struct({
15793
16089
  machine: String4,
15794
16090
  id: String4
@@ -15803,14 +16099,12 @@ var RuntimeMachine = Struct({
15803
16099
  });
15804
16100
  var InboxRow = Struct({
15805
16101
  id: Number5,
15806
- sessionId: String4,
16102
+ sender: NullOr(String4),
16103
+ recipient: NullOr(String4),
15807
16104
  kind: InboxKind,
15808
16105
  message: String4,
15809
- details: fromJsonString2(Record(String4, Unknown2)),
15810
- status: InboxStatus,
15811
- createdAt: Number5
16106
+ status: InboxStatus
15812
16107
  });
15813
-
15814
16108
  class HarnessUnavailable extends TaggedError3()("HarnessUnavailable", {
15815
16109
  harness: String4,
15816
16110
  message: String4
@@ -15847,14 +16141,9 @@ class AmbiguousSession extends TaggedError3()("AmbiguousSession", {
15847
16141
  }
15848
16142
  }
15849
16143
 
15850
- class ProjectMoved extends TaggedError3()("ProjectMoved", {
15851
- projectId: String4,
15852
- from: String4,
15853
- to: String4
16144
+ class MoveRefused extends TaggedError3()("MoveRefused", {
16145
+ message: String4
15854
16146
  }) {
15855
- get message() {
15856
- return `the project moved from ${this.from} to ${this.to}; run vibest here to move it`;
15857
- }
15858
16147
  }
15859
16148
 
15860
16149
  class AllocationFailed extends TaggedError3()("AllocationFailed", {
@@ -15880,9 +16169,28 @@ class NotReady extends TaggedError3()("NotReady", {
15880
16169
  }) {
15881
16170
  }
15882
16171
 
15883
- class NoHarnessChosen extends TaggedError3()("NoHarnessChosen", {}) {
16172
+ class NoCallingSession extends TaggedError3()("NoCallingSession", {}) {
15884
16173
  get message() {
15885
- return "no harness to inherit: name one, for example `vibest run claude -- <prompt>`";
16174
+ return "vibest run is run by an agent in a session; to start working, run vibest in a terminal";
16175
+ }
16176
+ }
16177
+
16178
+ class UnknownAgent extends TaggedError3()("UnknownAgent", {
16179
+ agent: String4,
16180
+ known: ArraySchema(Struct({ id: String4, description: String4 }))
16181
+ }) {
16182
+ get message() {
16183
+ const known = this.known.map((definition) => `${definition.id} (${definition.description})`).join("; ");
16184
+ return `no agent definition ${this.agent}; registered: ${known || "none"}`;
16185
+ }
16186
+ }
16187
+ var runnableNote = (runnable) => runnable.length === 0 ? "" : `; this machine can run: ${runnable.join(", ")}`;
16188
+
16189
+ class NoHarnessChosen extends TaggedError3()("NoHarnessChosen", {
16190
+ runnable: ArraySchema(String4)
16191
+ }) {
16192
+ get message() {
16193
+ return `no harness to inherit: name one, for example \`vibest run claude -- <prompt>\`${runnableNote(this.runnable)}`;
15886
16194
  }
15887
16195
  }
15888
16196
 
@@ -15896,6 +16204,18 @@ class NotInRepository extends TaggedError3()("NotInRepository", { path: String4
15896
16204
  return `${this.path} is not inside a git repository`;
15897
16205
  }
15898
16206
  }
16207
+ var HarnessModel = Struct({
16208
+ provider: NullOr(String4),
16209
+ model: String4,
16210
+ name: String4,
16211
+ default: Boolean3
16212
+ });
16213
+ var HarnessChoice = Struct({
16214
+ harness: String4,
16215
+ binary: String4,
16216
+ problem: NullOr(String4),
16217
+ models: ArraySchema(HarnessModel)
16218
+ });
15899
16219
 
15900
16220
  // ../../schema/src/subscription.ts
15901
16221
  var SubscriptionAccount = Struct({
@@ -16174,7 +16494,7 @@ class RpcClientError extends (/* @__PURE__ */ Error4(TypeId31)({
16174
16494
  }
16175
16495
 
16176
16496
  // ../../../node_modules/.pnpm/effect@4.0.2/node_modules/effect/dist/rpc/RpcMessage.js
16177
- var RequestId = (id) => id;
16497
+ var RequestId2 = (id) => id;
16178
16498
  var constPing = {
16179
16499
  _tag: "Ping"
16180
16500
  };
@@ -16835,7 +17155,7 @@ var make26 = /* @__PURE__ */ fnUntraced2(function* (group, options) {
16835
17155
  yield* run(clientId, (message) => {
16836
17156
  switch (message._tag) {
16837
17157
  case "Chunk": {
16838
- const requestId = RequestId(message.requestId);
17158
+ const requestId = RequestId2(message.requestId);
16839
17159
  const entry = entries.get(requestId);
16840
17160
  if (!entry || isNone2(entry.schemas.decodeChunk))
16841
17161
  return void_3;
@@ -16853,7 +17173,7 @@ var make26 = /* @__PURE__ */ fnUntraced2(function* (group, options) {
16853
17173
  }).pipe(andThen2(hasInterrupts2(cause) ? void_3 : ignore2(interruptRequest(requestId))))), catchCauseIf2((cause) => !hasInterrupts2(cause), () => void_3)));
16854
17174
  }
16855
17175
  case "Exit": {
16856
- const requestId = RequestId(message.requestId);
17176
+ const requestId = RequestId2(message.requestId);
16857
17177
  const entry = entries.get(requestId);
16858
17178
  if (!entry)
16859
17179
  return void_3;
@@ -17233,27 +17553,6 @@ var Service2 = () => (id, options) => {
17233
17553
  ServiceClass_.requiredForClient = options?.requiredForClient ?? false;
17234
17554
  return ServiceClass;
17235
17555
  };
17236
- // ../../protocol/package.json
17237
- var package_default = {
17238
- name: "@vibest/protocol",
17239
- version: "0.0.1-beta.18",
17240
- private: true,
17241
- license: "MIT",
17242
- type: "module",
17243
- exports: {
17244
- "./scripts/*": "./scripts/*.ts",
17245
- "./*": "./src/*.ts"
17246
- },
17247
- scripts: {
17248
- typecheck: "tsrs --noEmit --fast && tsrs --noEmit --fast -p tsconfig.scripts.json",
17249
- contract: "bun scripts/contract.ts"
17250
- },
17251
- dependencies: {
17252
- "@vibest/schema": "workspace:*",
17253
- effect: "catalog:"
17254
- }
17255
- };
17256
-
17257
17556
  // ../../protocol/src/rpc.ts
17258
17557
  var DaemonIdentity = Struct({
17259
17558
  pid: optional2(Number5),
@@ -17291,7 +17590,7 @@ var PingResult = Struct({
17291
17590
  ...DaemonIdentity.fields,
17292
17591
  capabilities: optional2(Record(String4, Boolean3))
17293
17592
  });
17294
- var VERSION = package_default.version;
17593
+
17295
17594
  class ProtocolRejected extends TaggedError3()("ProtocolRejected", {
17296
17595
  method: String4,
17297
17596
  protocol: NullOr(String4),
@@ -17319,11 +17618,6 @@ class Forbidden2 extends TaggedError3()("Forbidden", {
17319
17618
  }) {
17320
17619
  }
17321
17620
 
17322
- class ProjectCreateFailed extends TaggedError3()("ProjectCreateFailed", {
17323
- message: String4
17324
- }) {
17325
- }
17326
-
17327
17621
  class Caller extends Service()("vibest/Caller") {
17328
17622
  }
17329
17623
 
@@ -17371,7 +17665,8 @@ var GitInfo = Struct({
17371
17665
  branch: String4,
17372
17666
  pushed: Boolean3,
17373
17667
  saved: Boolean3,
17374
- why: String4
17668
+ why: String4,
17669
+ unknown: optional2(String4)
17375
17670
  });
17376
17671
  var SessionInfo = Struct({
17377
17672
  id: String4,
@@ -17383,7 +17678,7 @@ var SessionInfo = Struct({
17383
17678
  status: AgentStatus,
17384
17679
  startedAt: NullOr(Number5),
17385
17680
  exitedAt: NullOr(Number5),
17386
- turnState: TurnState,
17681
+ executionState: ExecutionState,
17387
17682
  projectId: String4,
17388
17683
  runtime: String4,
17389
17684
  address: RuntimeAddress,
@@ -17403,21 +17698,17 @@ var SessionInfo = Struct({
17403
17698
  view: optional2(String4)
17404
17699
  });
17405
17700
  var LINE_ERRORS = [UnknownMachine, MachineUnavailable, MachineIncompatible];
17406
- var InboxMessage = Struct({ ...InboxRow.fields, details: Record(String4, Unknown2) });
17407
- var SessionStatusInfo = Struct({ ...SessionInfo.fields, result: NullOr(InboxMessage) });
17408
- var HarnessModel = Struct({
17409
- provider: NullOr(String4),
17410
- model: String4,
17411
- name: String4,
17412
- default: Boolean3
17701
+ var SessionReply = Struct({
17702
+ execution: Number5,
17703
+ status: String4,
17704
+ text: NullOr(String4),
17705
+ failure: NullOr(String4),
17706
+ endedAt: Number5
17413
17707
  });
17414
- var HarnessChoice = Struct({
17415
- harness: String4,
17416
- binary: String4,
17417
- problem: NullOr(String4),
17418
- models: ArraySchema(HarnessModel)
17708
+ var SessionStatusInfo = Struct({
17709
+ ...SessionInfo.fields,
17710
+ reply: optional2(NullOr(SessionReply))
17419
17711
  });
17420
- var ProjectActivity = Literals(["blocked", "done", "working", "idle"]);
17421
17712
  var ProjectRow = Struct({
17422
17713
  id: String4,
17423
17714
  directory: NullOr(String4),
@@ -17427,7 +17718,7 @@ var ProjectRow = Struct({
17427
17718
  var WatchSession = Struct({
17428
17719
  ...SessionInfo.fields,
17429
17720
  parentId: NullOr(String4),
17430
- turn: NullOr(Number5)
17721
+ finished: NullOr(Number5)
17431
17722
  });
17432
17723
  var WatchEvent = Union2([
17433
17724
  TaggedStruct("Snapshot", { projects: ArraySchema(ProjectRow), sessions: ArraySchema(WatchSession) }),
@@ -17435,9 +17726,17 @@ var WatchEvent = Union2([
17435
17726
  TaggedStruct("Session", { session: WatchSession }),
17436
17727
  TaggedStruct("SessionEnded", { id: String4, projectId: String4 })
17437
17728
  ]);
17729
+ var EventsFact = Struct({
17730
+ aggregate: String4,
17731
+ seq: Number5,
17732
+ at: Number5,
17733
+ type: String4,
17734
+ data: Unknown2
17735
+ });
17438
17736
 
17439
17737
  class WatchLagged extends TaggedError3()("WatchLagged", { message: String4 }) {
17440
17738
  }
17739
+ var Attachments = optional2(ArraySchema(Struct({ name: String4, content: Uint8ArrayFromBase64 })));
17441
17740
 
17442
17741
  class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4(admitted(make25("Spawn", {
17443
17742
  payload: {
@@ -17447,14 +17746,15 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17447
17746
  provider: optional2(String4),
17448
17747
  model: optional2(String4),
17449
17748
  env: optional2(Record(String4, String4)),
17450
- agent: optional2(String4),
17749
+ agent: String4,
17451
17750
  callerEnv: Record(String4, String4),
17452
17751
  runtimeSession: optional2(String4),
17453
- peer: optional2(String4),
17752
+ share: optional2(String4),
17454
17753
  archive: optional2(Boolean3),
17455
17754
  runtime: optional2(String4),
17456
17755
  request: optional2(String4),
17457
- machine: optional2(String4)
17756
+ machine: optional2(String4),
17757
+ files: Attachments
17458
17758
  },
17459
17759
  success: Struct({
17460
17760
  id: String4,
@@ -17478,20 +17778,23 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17478
17778
  AllocationFailed,
17479
17779
  HarnessUnavailable,
17480
17780
  NotInRepository,
17481
- ProjectMoved,
17781
+ NoCallingSession,
17482
17782
  NoHarnessChosen,
17483
17783
  NoRuntime,
17484
17784
  AgentRefused,
17785
+ PluginsNotActive,
17786
+ UnknownAgent,
17485
17787
  NoSuchSession,
17486
17788
  AmbiguousSession,
17487
17789
  RuntimeUnreachable,
17488
17790
  RuntimeIncompatible
17489
17791
  ])
17490
17792
  }))), protocol(make25("Plugins", { success: ArraySchema(PluginInfo) })), protocol(make25("Harnesses.List", {
17491
- payload: { provider: optional2(String4) },
17492
- success: ArraySchema(HarnessChoice)
17793
+ payload: { provider: optional2(String4), machine: optional2(String4) },
17794
+ success: ArraySchema(HarnessChoice),
17795
+ error: Union2([Forbidden2, ...LINE_ERRORS])
17493
17796
  })), scoped4(make25("Integration.Guard", {
17494
- payload: { harness: String4, agent: String4, input: String4 },
17797
+ payload: { harness: String4, input: String4 },
17495
17798
  success: Struct({ answer: optional2(Unknown2) }),
17496
17799
  error: Union2([HarnessUnavailable, InvalidCaller])
17497
17800
  })), protocol(make25("Runtimes.Doctor", {
@@ -17500,6 +17803,7 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17500
17803
  })), protocol(make25("Subscriptions", { success: ArraySchema(Subscription) })), protocol(make25("Republish", { success: Number5 })), scoped4(admitted(make25("Launch", {
17501
17804
  payload: {
17502
17805
  argv: ArraySchema(String4),
17806
+ agent: String4,
17503
17807
  focus: Boolean3,
17504
17808
  callerEnv: Record(String4, String4),
17505
17809
  runtimeSession: optional2(String4),
@@ -17516,13 +17820,14 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17516
17820
  InvalidCaller,
17517
17821
  Forbidden2,
17518
17822
  NotInRepository,
17519
- ProjectMoved,
17520
17823
  LaunchFailed,
17521
17824
  NoRuntime,
17522
- AgentRefused
17825
+ AgentRefused,
17826
+ PluginsNotActive,
17827
+ UnknownAgent
17523
17828
  ])
17524
17829
  }))), scoped4(admitted(make25("Send", {
17525
- payload: { id: String4, message: String4, request: optional2(String4) },
17830
+ payload: { id: String4, message: String4, request: optional2(RequestId) },
17526
17831
  success: Struct({ id: String4 }),
17527
17832
  error: Union2([Forbidden2, NoSuchSession, AmbiguousSession, ...LINE_ERRORS])
17528
17833
  }))), scoped4(admitted(make25("Interrupt", {
@@ -17565,16 +17870,34 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17565
17870
  view: optional2(String4)
17566
17871
  }),
17567
17872
  error: Union2([Forbidden2, NoSuchSession, AmbiguousSession, NoRuntime, RuntimeUnreachable, ...LINE_ERRORS])
17568
- })), scoped4(admitted(make25("Report", { payload: { message: String4 }, error: Union2([Forbidden2, NoSuchSession]) }))), scoped4(make25("Inbox.Subscribe", { success: String4, error: Union2([Forbidden2]), stream: true })), scoped4(make25("Watch", { success: WatchEvent, error: Union2([Forbidden2, WatchLagged]), stream: true })), scoped4(admitted(make25("Session.Seen", {
17569
- payload: { id: String4, turn: Number5 },
17873
+ })), scoped4(make25("Inbox.Subscribe", { success: Null2, error: Union2([Forbidden2]), stream: true })), scoped4(make25("Inbox.Take", {
17874
+ success: NullOr(Struct({
17875
+ execution: Number5,
17876
+ ids: ArraySchema(Number5),
17877
+ line: String4,
17878
+ text: String4
17879
+ })),
17880
+ error: Union2([Forbidden2])
17881
+ })), scoped4(make25("Events", {
17882
+ payload: {
17883
+ session: optional2(String4),
17884
+ after: optional2(Int.check(isGreaterThanOrEqualTo2(0))),
17885
+ follow: optional2(Boolean3)
17886
+ },
17887
+ success: EventsFact,
17888
+ error: Union2([Forbidden2, NoSuchSession]),
17889
+ stream: true
17890
+ })), scoped4(make25("Watch", { success: WatchEvent, error: Union2([Forbidden2, WatchLagged]), stream: true })), scoped4(admitted(make25("Session.Seen", {
17891
+ payload: { id: String4, finished: Number5 },
17570
17892
  error: Union2([Forbidden2, NoSuchSession, RuntimeUnreachable])
17571
- }))), protocol(admitted(make25("TurnEnd", {
17893
+ }))), protocol(admitted(make25("ExecutionEnd", {
17572
17894
  payload: { sessionId: String4, harness: String4, event: String4 }
17573
17895
  }))), protocol(admitted(make25("Prompt", {
17574
17896
  payload: { sessionId: String4, harness: String4, event: String4 }
17575
- }))), scoped4(admitted(make25("Project.CoordinatorSession", {
17897
+ }))), scoped4(admitted(make25("Project.EntrySession", {
17576
17898
  payload: {
17577
17899
  harness: String4,
17900
+ agent: String4,
17578
17901
  fresh: Boolean3,
17579
17902
  terminal: String4,
17580
17903
  runtime: optional2(String4),
@@ -17598,15 +17921,16 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17598
17921
  InvalidCaller,
17599
17922
  Forbidden2,
17600
17923
  NotInRepository,
17601
- ProjectMoved,
17602
17924
  RuntimeUnreachable,
17603
17925
  RuntimeIncompatible,
17604
17926
  HarnessUnavailable,
17605
- LaunchFailed
17927
+ LaunchFailed,
17928
+ UnknownAgent
17606
17929
  ])
17607
- }))), scoped4(make25("Project.StartMain", {
17930
+ }))), scoped4(make25("Project.StartEntry", {
17608
17931
  payload: {
17609
17932
  harness: optional2(String4),
17933
+ agent: String4,
17610
17934
  provider: optional2(String4),
17611
17935
  model: optional2(String4),
17612
17936
  runtime: optional2(String4)
@@ -17622,27 +17946,29 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17622
17946
  InvalidCaller,
17623
17947
  Forbidden2,
17624
17948
  NotInRepository,
17625
- ProjectMoved,
17626
17949
  NoHarnessChosen,
17627
17950
  AgentRefused,
17951
+ PluginsNotActive,
17628
17952
  HarnessUnavailable,
17629
17953
  NoRuntime,
17630
- LaunchFailed
17954
+ LaunchFailed,
17955
+ UnknownAgent
17631
17956
  ])
17632
17957
  })), scoped4(make25("Project.Open", {
17633
- payload: { move: optional2(Boolean3) },
17958
+ payload: {},
17959
+ success: Struct({ projectId: String4, directory: String4 }),
17960
+ error: Union2([Forbidden2, NotInRepository])
17961
+ })), scoped4(make25("Project.Move", {
17962
+ payload: { from: String4 },
17634
17963
  success: Struct({
17635
17964
  projectId: String4,
17636
17965
  directory: String4,
17637
- moved: optional2(Struct({
17638
- from: String4,
17639
- repaired: ArraySchema(String4),
17640
- manual: ArraySchema(String4)
17641
- })),
17642
- candidates: optional2(ArraySchema(String4))
17966
+ from: String4,
17967
+ repaired: ArraySchema(String4),
17968
+ manual: ArraySchema(String4)
17643
17969
  }),
17644
- error: Union2([Forbidden2, NotInRepository, ProjectMoved])
17645
- })), scoped4(make25("Project.MainPlace", {
17970
+ error: Union2([Forbidden2, NotInRepository, MoveRefused])
17971
+ })), scoped4(make25("Project.EntryPlace", {
17646
17972
  payload: {
17647
17973
  callerEnv: Record(String4, String4),
17648
17974
  runtime: optional2(String4)
@@ -17661,12 +17987,12 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17661
17987
  })
17662
17988
  ])
17663
17989
  }),
17664
- error: Union2([InvalidCaller, Forbidden2, NotInRepository, ProjectMoved, LaunchFailed])
17665
- })), scoped4(make25("Project.FocusCoordinator", {
17990
+ error: Union2([InvalidCaller, Forbidden2, NotInRepository, LaunchFailed])
17991
+ })), scoped4(make25("Project.FocusEntry", {
17666
17992
  payload: {},
17667
17993
  success: NullOr(Struct({ place: String4, focused: Boolean3 })),
17668
- error: Union2([Forbidden2, NotInRepository, ProjectMoved])
17669
- })), scoped4(make25("Project.RunningCoordinator", {
17994
+ error: Union2([Forbidden2, NotInRepository])
17995
+ })), scoped4(make25("Project.RunningEntry", {
17670
17996
  payload: { terminal: String4 },
17671
17997
  success: NullOr(Struct({
17672
17998
  harness: String4,
@@ -17674,30 +18000,21 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17674
18000
  runtime: String4,
17675
18001
  address: String4
17676
18002
  })),
17677
- error: Union2([
17678
- InvalidCaller,
17679
- Forbidden2,
17680
- NotInRepository,
17681
- ProjectMoved,
17682
- RuntimeUnreachable,
17683
- RuntimeIncompatible
17684
- ])
17685
- })), scoped4(admitted(make25("Project.StopCoordinator", {
18003
+ error: Union2([InvalidCaller, Forbidden2, NotInRepository, RuntimeUnreachable, RuntimeIncompatible])
18004
+ })), scoped4(admitted(make25("Project.StopEntry", {
17686
18005
  payload: { runtime: String4, address: String4 },
17687
18006
  success: Struct({
17688
18007
  result: Literals(["stopped", "running", "moved", "unsupported"]),
17689
18008
  reason: optional2(String4)
17690
18009
  }),
17691
- error: Union2([Forbidden2, NotInRepository, ProjectMoved, RuntimeUnreachable, NoRuntime, InvalidCaller])
17692
- }))), protocol(admitted(make25("CoordinatorSessionReady", {
17693
- payload: { sessionId: String4, harness: String4, harnessSessionId: String4 }
18010
+ error: Union2([Forbidden2, NotInRepository, RuntimeUnreachable, NoRuntime, InvalidCaller])
17694
18011
  }))), scoped4(make25("Project.Info", {
17695
18012
  success: ProjectInfoResult,
17696
- error: Union2([Forbidden2, NotInRepository, ProjectMoved])
18013
+ error: Union2([Forbidden2, NotInRepository])
17697
18014
  })), scoped4(make25("Project.Search", {
17698
18015
  payload: ProjectSearchInput.fields,
17699
18016
  success: ArraySchema(String4),
17700
- error: Union2([Forbidden2, NotInRepository, ProjectMoved])
18017
+ error: Union2([Forbidden2, NotInRepository])
17701
18018
  })), scoped4(admitted(make25("Project.Create", {
17702
18019
  payload: { directory: String4, from: ArraySchema(String4) },
17703
18020
  success: Struct({
@@ -17721,7 +18038,12 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17721
18038
  success: Struct({ instance: String4 }),
17722
18039
  error: Union2([Forbidden2, WrongInstance, DaemonBusy, DaemonStopping, LaunchFailed])
17723
18040
  })), scoped4(make25("Session.Ready", {
17724
- payload: { id: String4, pid: optional2(Number5) },
18041
+ payload: {
18042
+ id: String4,
18043
+ pid: optional2(Number5),
18044
+ conversation: optional2(Struct({ harness: String4, id: String4 }))
18045
+ },
18046
+ success: Struct({ process: optional2(Number5) }),
17725
18047
  error: Union2([Forbidden2, NoSuchSession])
17726
18048
  })), scoped4(make25("Agents.Outdated", {
17727
18049
  success: ArraySchema(Struct({
@@ -17750,15 +18072,15 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17750
18072
  repository: String4,
17751
18073
  identity: optional2(String4),
17752
18074
  commit: String4,
18075
+ agent: String4,
17753
18076
  prompt: String4,
17754
18077
  harness: optional2(String4),
17755
18078
  provider: optional2(String4),
17756
18079
  model: optional2(String4),
17757
18080
  title: optional2(String4),
17758
18081
  runtime: optional2(String4),
17759
- parent: optional2(String4),
17760
- reportTo: optional2(String4),
17761
- request: String4
18082
+ request: String4,
18083
+ files: Attachments
17762
18084
  },
17763
18085
  success: Struct({
17764
18086
  session: String4,
@@ -17777,9 +18099,12 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17777
18099
  LimitReached,
17778
18100
  AllocationFailed,
17779
18101
  HarnessUnavailable,
18102
+ NoCallingSession,
17780
18103
  NoHarnessChosen,
17781
18104
  NoRuntime,
17782
18105
  AgentRefused,
18106
+ PluginsNotActive,
18107
+ UnknownAgent,
17783
18108
  NoSuchSession,
17784
18109
  RuntimeUnreachable,
17785
18110
  RuntimeIncompatible
@@ -17803,33 +18128,34 @@ class VibestRpcs extends make27(make25("Ping", { success: PingResult }), scoped4
17803
18128
  var ACCESS = {
17804
18129
  Ping: ["open", "peer"],
17805
18130
  Plugins: "open",
17806
- "Harnesses.List": "open",
18131
+ "Harnesses.List": ["open", "peer"],
17807
18132
  "Integration.Guard": "open",
17808
18133
  "Runtimes.Doctor": "open",
17809
18134
  Subscriptions: "open",
17810
18135
  Republish: "open",
17811
- TurnEnd: "open",
18136
+ ExecutionEnd: "open",
17812
18137
  Prompt: "open",
17813
- CoordinatorSessionReady: "open",
17814
- Report: "session",
17815
18138
  Spawn: "agent",
17816
- Launch: "agent",
18139
+ Launch: "cli",
17817
18140
  List: ["agent", "peer"],
17818
18141
  Get: ["agent", "peer"],
17819
- "Inbox.Subscribe": "coordinator",
18142
+ "Inbox.Subscribe": "session",
18143
+ "Inbox.Take": "session",
17820
18144
  Watch: "cli",
18145
+ Events: "cli",
17821
18146
  "Session.Seen": "cli",
17822
18147
  "Project.Open": "cli",
17823
- "Project.MainPlace": "cli",
17824
- "Project.CoordinatorSession": "agent",
17825
- "Project.StartMain": "agent",
17826
- "Project.FocusCoordinator": "cli",
17827
- "Project.RunningCoordinator": "agent",
17828
- "Project.StopCoordinator": "agent",
18148
+ "Project.Move": "cli",
18149
+ "Project.EntryPlace": "cli",
18150
+ "Project.EntrySession": "cli",
18151
+ "Project.StartEntry": "cli",
18152
+ "Project.FocusEntry": "cli",
18153
+ "Project.RunningEntry": "agent",
18154
+ "Project.StopEntry": "cli",
17829
18155
  "Project.Create": "cli",
17830
18156
  "Project.Info": "agent",
17831
18157
  "Project.Search": "agent",
17832
- Send: ["owner", "peer"],
18158
+ Send: ["owner", "session", "peer"],
17833
18159
  Interrupt: ["owner", "peer"],
17834
18160
  Peek: ["owner", "peer"],
17835
18161
  Remove: ["owner", "peer"],
@@ -17846,7 +18172,8 @@ var ACCESS = {
17846
18172
  "Machine.List": "cli",
17847
18173
  "Machine.Remove": "cli"
17848
18174
  };
17849
- var PEER_CALLS = new Set(Object.entries(ACCESS).filter(([, access]) => [].concat(access).includes("peer")).map(([method]) => method));
18175
+ var PEER_CALLS = new Set(Object.entries(ACCESS).filter(([, access]) => [access].flat().includes("peer")).map(([method]) => method));
18176
+ var FORWARDED_CALLS = new Set([...PEER_CALLS].filter((method) => method !== "Ping" && method !== "Harnesses.List" && !method.startsWith("Peer.")));
17850
18177
 
17851
18178
  // ../../schema/src/layout.ts
17852
18179
  class Layout extends Service()("vibest/Layout") {
@@ -17858,6 +18185,7 @@ class Layout extends Service()("vibest/Layout") {
17858
18185
  socket: path.join(home, "vibest.sock"),
17859
18186
  httpSocket: path.join(home, "vibest-http.sock"),
17860
18187
  daemonInfo: path.join(home, "vibestd.pid"),
18188
+ log: path.join(home, "vibestd.log"),
17861
18189
  identity: path.join(home, "identity.json"),
17862
18190
  worktrees: path.join(home, "worktrees"),
17863
18191
  projects: path.join(home, "projects"),
@@ -17865,7 +18193,8 @@ class Layout extends Service()("vibest/Layout") {
17865
18193
  plugins: path.join(home, "plugins"),
17866
18194
  allocationWorktree: (repository, name) => path.join(home, "worktrees", repository, name),
17867
18195
  project: (projectId) => path.join(home, "projects", projectId),
17868
- artifacts: (projectId) => path.join(home, "projects", projectId, "artifacts")
18196
+ artifacts: (projectId) => path.join(home, "projects", projectId, "artifacts"),
18197
+ sessionFolder: (projectId, sessionId) => path.join(home, "projects", projectId, "sessions", sessionId)
17869
18198
  });
17870
18199
  });
17871
18200
  static layer = effect(Layout, gen2(function* () {
@@ -17879,11 +18208,13 @@ var VibestCommand = Reference("vibest/VibestCommand", {
17879
18208
  });
17880
18209
  var shellQuote = (s) => /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
17881
18210
  // ../../client/src/socket-connector.ts
17882
- class SocketConnector extends Service()("vibest/SocketConnector") {
18211
+ class Service3 extends Service()("vibest/SocketConnector") {
17883
18212
  }
17884
18213
 
17885
18214
  // ../../client/src/client.ts
17886
- var DAEMON_START_TIMEOUT = seconds(10);
18215
+ var SHUTDOWN_DEADLINE = seconds(10);
18216
+ var SHUTDOWN_FLUSH = millis(1500);
18217
+ var DAEMON_START_TIMEOUT = sum(sum(SHUTDOWN_DEADLINE, SHUTDOWN_FLUSH), seconds(10));
17887
18218
 
17888
18219
  class DaemonUnavailable extends TaggedError3()("DaemonUnavailable", {
17889
18220
  socket: String4,
@@ -17913,10 +18244,13 @@ class IncompatibleDaemon extends TaggedError3()("IncompatibleDaemon", {
17913
18244
  const byHand = stopByHand(this.socket, this.daemon.pid).replace(/^To replace it, /, "");
17914
18245
  if (this.missing !== undefined)
17915
18246
  return `vibestd is older (${this.daemonVersion || "unknown"}); run ${MISMATCH_ACTION}. ${described(this.daemonVersion, this.daemon)} on ${this.socket} has no ${this.missing}, which ${self} needs. If \`vibest daemon restart\` cannot replace it: ${byHand}.`;
18247
+ if (this.daemonProtocol !== null && this.daemonProtocol > PROTOCOL)
18248
+ return `${self} speaks protocol ${PROTOCOL}, older than ${described(this.daemonVersion, this.daemon)} on ${this.socket}, which speaks ${got}. Run ${MISMATCH_ACTION} (again, if this was ${MISMATCH_ACTION}): the newest vibest finishes the update and restarts the agents still on the old integration. To keep vibest ${this.client.version} instead (\`vibest daemon restart\` cannot, as vibestd refuses this older protocol): ${byHand}.`;
17916
18249
  const mismatch = protocolMismatch(PROTOCOL, this.daemonProtocol ?? 0, this.daemonVersion || "unknown", this.client.version);
17917
18250
  return `${mismatch.message}. ${described(this.daemonVersion, this.daemon)} on ${this.socket} speaks ${got}; ${self} speaks protocol ${PROTOCOL}. If \`vibest daemon restart\` cannot replace it: ${byHand}. A package-version difference alone does not require a restart.`;
17918
18251
  }
17919
18252
  }
18253
+ var Claim = taggedEnum();
17920
18254
  var protocolHeaders = () => ({ [PROTOCOL_HEADER]: String(PROTOCOL) });
17921
18255
  var cliHeaders = (repositoryRoot) => ({
17922
18256
  ...protocolHeaders(),
@@ -17927,30 +18261,32 @@ var fromEnv2 = gen2(function* () {
17927
18261
  const read = (name) => option3(String5(name)).pipe(map6((v) => getOrUndefined(v) || undefined));
17928
18262
  return {
17929
18263
  projectId: yield* read("VIBEST_PROJECT_ID"),
17930
- agent: yield* read("VIBEST_AGENT"),
17931
18264
  harness: yield* read("VIBEST_HARNESS"),
17932
18265
  runtime: yield* read("VIBEST_RUNTIME"),
18266
+ process: yield* read("VIBEST_PROCESS"),
17933
18267
  cwd: (yield* Path).resolve(".")
17934
18268
  };
17935
- }).pipe(orElseSucceed2(() => ({})));
17936
- var claimHeaders = (claim) => claim._tag === "cli" ? succeed7(cliHeaders(claim.repositoryRoot)) : map6(fromEnv2, (more) => sessionHeaders({
18269
+ }).pipe(tapCause2((cause) => logDebug("session claim headers fell back to the request", cause)), orElseSucceed2(() => ({})));
18270
+ var claimHeaders = (claim) => isTagged(claim, "cli") ? succeed7(cliHeaders(claim.repositoryRoot)) : map6(fromEnv2, (more) => sessionHeaders({
17937
18271
  ...more,
17938
18272
  sessionId: claim.sessionId,
17939
18273
  repositoryRoot: claim.repositoryRoot,
17940
18274
  harnessSessionId: claim.harnessSessionId,
17941
- pluginVersion: claim.pluginVersion
18275
+ pluginVersion: claim.pluginVersion,
18276
+ ...claim.process !== undefined && { process: claim.process }
17942
18277
  }));
17943
- var connect2 = (socket) => build(layerProtocolSocket({ pingInterval: "1 minute", pingTimeout: "1 day" }).pipe(provide2(effect(Socket, flatMap4(SocketConnector, (dial) => dial(socket)))), provide2(layerNdJsonRpc()))).pipe(flatMap4((protocol) => make26(VibestRpcs).pipe(provide4(protocol))));
18278
+ var clientOver = (socket, options) => build(layerProtocolSocket(options).pipe(provide2(socket), provide2(layerNdJsonRpc()))).pipe(flatMap4((protocol) => make26(VibestRpcs).pipe(provide4(protocol))));
18279
+ var connect2 = (socket) => clientOver(effect(Socket, flatMap4(Service3, (dial) => dial(socket))), { pingInterval: "1 minute", pingTimeout: "1 day" });
17944
18280
  var HOOK_TIMEOUT = seconds(2);
17945
18281
  var HOOK_RETRY_DELAY = millis(300);
17946
18282
  var CONNECT_CODES = new Set(["ECONNREFUSED", "ENOENT"]);
17947
- var notConnected = (error) => {
17948
- if (!hasProperty(error, "reason") || !hasProperty(error.reason, "_tag"))
18283
+ var notConnected = (cause) => {
18284
+ if (!hasProperty(cause, "reason"))
17949
18285
  return false;
17950
- if (error.reason._tag !== "SocketOpenError" || !hasProperty(error.reason, "cause"))
18286
+ if (!isTagged(cause.reason, "SocketOpenError") || !hasProperty(cause.reason, "cause"))
17951
18287
  return false;
17952
- const cause = error.reason.cause;
17953
- return hasProperty(cause, "code") && isString(cause.code) && CONNECT_CODES.has(cause.code);
18288
+ const socketCause = cause.reason.cause;
18289
+ return hasProperty(socketCause, "code") && isString(socketCause.code) && CONNECT_CODES.has(socketCause.code);
17954
18290
  };
17955
18291
  var hookCall = (socket, headers, send) => {
17956
18292
  const once = withHeaders(connect2(socket).pipe(flatMap4(send)), headers).pipe(scoped2, timeout2(HOOK_TIMEOUT), exit2);
@@ -17965,28 +18301,27 @@ var hookCall = (socket, headers, send) => {
17965
18301
  var readPing = (socket) => connect2(socket).pipe(flatMap4((client) => client.Ping(undefined)), timeout2("1 second"), option2, catchCause2((cause) => hasInterruptsOnly2(cause) ? succeed7(none2()) : failCause3(cause)), scoped2);
17966
18302
  var probe = (socket) => readPing(socket).pipe(map6(isSome2), orElseSucceed2(() => false));
17967
18303
  var awaitDaemon = (socket) => probe(socket).pipe(repeat2({ until: (up) => up, schedule: spaced("200 millis") }), timeoutOrElse2({ duration: DAEMON_START_TIMEOUT, orElse: () => succeed7(false) }));
17968
- var incompatibleDaemon = (socket, ping, self, needs) => {
18304
+ var incompatibleDaemon = (socket, ping, client, needs) => {
17969
18305
  const lacks = needs !== undefined && ping.capabilities?.[needs.capability] !== true;
17970
18306
  return ping.protocol === PROTOCOL && !lacks ? undefined : new IncompatibleDaemon({
17971
18307
  socket,
17972
18308
  daemonVersion: ping.version,
17973
18309
  daemonProtocol: ping.protocol ?? null,
17974
18310
  daemon: { pid: ping.pid, instance: ping.instance, command: ping.command, startedAt: ping.startedAt },
17975
- client: { version: VERSION, command: self },
17976
- ...ping.protocol === PROTOCOL && needs !== undefined ? { missing: needs.method } : {}
18311
+ client,
18312
+ ...ping.protocol === PROTOCOL && needs !== undefined && { missing: needs.method }
17977
18313
  });
17978
18314
  };
17979
18315
  var spawnDaemon = (command, args = [], env) => gen2(function* () {
17980
18316
  const layout = yield* Layout;
17981
- const path = yield* Path;
17982
18317
  const spawner = yield* ChildProcessSpawner;
17983
- const log = path.join(layout.home, "vibestd.log");
17984
18318
  yield* gen2(function* () {
17985
18319
  const handle = yield* spawner.spawn(make13("sh", [
17986
18320
  "-c",
17987
- `mkdir -p "$1" && shift && exec "$@" >>"${log}" 2>&1`,
18321
+ 'mkdir -p "$1" && log=$2 && shift 2 && { "$@" >>"$log" 2>&1 & }',
17988
18322
  "sh",
17989
18323
  layout.home,
18324
+ layout.log,
17990
18325
  ...command,
17991
18326
  "daemon",
17992
18327
  "--foreground",
@@ -17997,30 +18332,34 @@ var spawnDaemon = (command, args = [], env) => gen2(function* () {
17997
18332
  extendEnv: true,
17998
18333
  stdin: "ignore",
17999
18334
  stdout: "ignore",
18000
- stderr: "ignore"
18335
+ stderr: "pipe"
18001
18336
  }));
18002
18337
  yield* handle.unref;
18338
+ const [said, code] = yield* all2([mkString(decodeText(handle.stderr)), handle.exitCode], {
18339
+ concurrency: "unbounded"
18340
+ });
18341
+ if (code !== 0)
18342
+ return yield* fail6(new Error(`vibestd was not started (exit ${code}): ${said.trim() || "no output"}`));
18003
18343
  }).pipe(scoped2, mapError3((e) => new DaemonUnavailable({ socket: layout.socket, message: e.message })));
18004
18344
  });
18005
18345
  var startDaemon = gen2(function* () {
18006
18346
  const layout = yield* Layout;
18007
- const path = yield* Path;
18008
18347
  const fs = yield* FileSystem;
18009
- const log = path.join(layout.home, "vibestd.log");
18010
- const logAt = yield* fs.stat(log).pipe(map6((info) => Number(info.size)), orElseSucceed2(() => 0));
18348
+ const logAt = yield* fs.stat(layout.log).pipe(map6((info) => Number(info.size)), orElseSucceed2(() => 0));
18011
18349
  yield* spawnDaemon(yield* VibestCommand);
18012
18350
  if (yield* awaitDaemon(layout.socket))
18013
18351
  return;
18014
- const bytes = yield* fs.readFile(log).pipe(orElseSucceed2(() => new Uint8Array));
18015
- const text = Array.from(bytes.subarray(logAt), (b) => String.fromCharCode(b)).join("");
18352
+ const bytes = yield* fs.readFile(layout.log).pipe(orElseSucceed2(() => new Uint8Array));
18353
+ const from = bytes.length < logAt ? 0 : logAt;
18354
+ const text = Array.from(bytes.subarray(from), (b) => String.fromCharCode(b)).join("");
18016
18355
  const tagged = text.split(`
18017
18356
  `).map((line) => /^([A-Z][A-Za-z0-9]*): (.+)$/.exec(line.trim())).filter((m) => m !== null).at(-1);
18018
18357
  return yield* new DaemonUnavailable({
18019
18358
  socket: layout.socket,
18020
- message: tagged ? `${tagged[1]}: ${tagged[2]}` : `vibestd did not come up; see ${log}`
18359
+ message: tagged ? `${tagged[1]}: ${tagged[2]}` : `vibestd did not come up; see ${layout.log}`
18021
18360
  });
18022
18361
  });
18023
- var withVibest = (claim, f, options) => gen2(function* () {
18362
+ var withVibest = (version) => (claim, f, options) => gen2(function* () {
18024
18363
  const layout = yield* Layout;
18025
18364
  const up = yield* readPing(layout.socket);
18026
18365
  if (isNone2(up)) {
@@ -18037,22 +18376,33 @@ var withVibest = (claim, f, options) => gen2(function* () {
18037
18376
  socket: layout.socket,
18038
18377
  message: `vibestd did not answer Ping on ${layout.socket}`
18039
18378
  });
18040
- const incompatible = incompatibleDaemon(layout.socket, ping, yield* VibestCommand, options?.needs);
18379
+ const incompatible = incompatibleDaemon(layout.socket, ping, { version, command: yield* VibestCommand }, options?.needs);
18041
18380
  if (incompatible)
18042
18381
  return yield* incompatible;
18043
18382
  return yield* withHeaders(connect2(layout.socket).pipe(flatMap4((client) => f(client, ping))), yield* claimHeaders(claim));
18044
18383
  }).pipe(scoped2);
18384
+ var makeClient = (options) => ({ withVibest: withVibest(options.version) });
18045
18385
 
18046
18386
  // src/pi.ts
18387
+ var registrars = (api) => ({
18388
+ session_start: (handler) => api.on("session_start", handler),
18389
+ resources_discover: (handler) => api.on("resources_discover", handler),
18390
+ before_agent_start: (handler) => api.on("before_agent_start", handler),
18391
+ input: (handler) => api.on("input", handler),
18392
+ tool_call: (handler) => api.on("tool_call", handler),
18393
+ message_start: (handler) => api.on("message_start", handler),
18394
+ agent_end: (handler) => api.on("agent_end", handler),
18395
+ agent_settled: (handler) => api.on("agent_settled", handler)
18396
+ });
18397
+
18047
18398
  class Pi extends Service()("@vibest/pi/Pi") {
18048
18399
  static layer = (api) => succeed6(Pi, Pi.of({
18049
18400
  handle: (event, f) => gen2(function* () {
18050
18401
  const run = yield* makeRuntimePromise();
18051
- const on = api.on;
18052
- yield* acquireRelease2(sync2(() => on(event, (e, ctx) => run(f(e, ctx)))), (off) => sync2(off));
18402
+ const on = registrars(api)[event];
18403
+ yield* acquireRelease2(sync2(() => on((e, ctx) => run(f(e, ctx)))), (off) => sync2(off));
18053
18404
  }),
18054
- sendMessage: (...args) => sync2(() => api.sendMessage(...args)),
18055
- load: (factory) => sync2(() => factory(api))
18405
+ sendMessage: (...args) => sync2(() => api.sendMessage(...args))
18056
18406
  }));
18057
18407
  static runMain = (api, extension) => runPromise2(gen2(function* () {
18058
18408
  const scope = yield* make6();
@@ -18061,856 +18411,29 @@ class Pi extends Service()("@vibest/pi/Pi") {
18061
18411
  }));
18062
18412
  }
18063
18413
 
18064
- // src/tui/tool-groups.ts
18065
- import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
18066
- function tool_groups_default(pi) {
18067
- let open = null;
18068
- let runActive = false;
18069
- const groups = [];
18070
- const byId = new Map;
18071
- const calls = new Map;
18072
- const invalidators = new Map;
18073
- const expandedById = new Map;
18074
- let bodyGroup = new WeakMap;
18075
- let replaying = false;
18076
- function gutter(width, outputPad) {
18077
- const room = Math.max(1, Math.floor(width) || 1);
18078
- let pad = Math.max(0, Math.floor(Number(outputPad) || 0));
18079
- if (pad * 2 >= room)
18080
- pad = Math.max(0, Math.floor((room - 1) / 2));
18081
- return { pad, limit: Math.max(1, room - pad * 2) };
18082
- }
18083
- function indent(lines, pad) {
18084
- if (!pad)
18085
- return lines;
18086
- const prefix = " ".repeat(pad);
18087
- return lines.map((line) => prefix + line);
18088
- }
18089
- function frameLines(renderers, component, width, outputPad) {
18090
- if (renderers?.renderShell === "self")
18091
- return component.render(width);
18092
- const { pad, limit } = gutter(width, outputPad);
18093
- return indent(component.render(limit), pad);
18094
- }
18095
- function frameComponent(renderers, component, outputPad) {
18096
- if (renderers?.renderShell === "self")
18097
- return component;
18098
- return {
18099
- invalidate() {
18100
- component.invalidate?.();
18101
- },
18102
- render(width) {
18103
- return frameLines(renderers, component, width, outputPad);
18104
- }
18105
- };
18106
- }
18107
- function wrapText(text, width) {
18108
- return wrapTextWithAnsi(String(text ?? ""), Math.max(1, width || 1));
18109
- }
18110
- function oneLine(text, limit) {
18111
- const flat = String(text ?? "").replace(/\s+/g, " ").trim();
18112
- if (!flat)
18113
- return "";
18114
- if (flat.length <= limit)
18115
- return flat;
18116
- return flat.slice(0, Math.max(1, limit - 1)) + "…";
18117
- }
18118
- function primaryArg(name, args) {
18119
- if (args === undefined || args === null)
18120
- return "";
18121
- if (typeof args !== "object" || Array.isArray(args))
18122
- return oneLine(typeof args === "string" ? args : JSON.stringify(args), 40);
18123
- const preferred = {
18124
- read: ["path", "file_path"],
18125
- write: ["path", "file_path"],
18126
- edit: ["path", "file_path"],
18127
- ls: ["path"],
18128
- bash: ["command"],
18129
- powershell: ["command"],
18130
- grep: ["pattern"],
18131
- find: ["pattern", "path"],
18132
- tool_search: ["query"]
18133
- }[name] || ["path", "file_path", "command", "query", "pattern", "url"];
18134
- const sensitive = /token|secret|password|authorization|credential|api[_-]?key/i;
18135
- for (const key of preferred) {
18136
- if (sensitive.test(key))
18137
- continue;
18138
- const value = args[key];
18139
- if (typeof value === "string" && value)
18140
- return oneLine(value, 40);
18141
- }
18142
- for (const [key, value] of Object.entries(args)) {
18143
- if (sensitive.test(key) || key === "script" || key === "content" || key === "edits")
18144
- continue;
18145
- if (typeof value === "string" && value)
18146
- return oneLine(value, 40);
18147
- }
18148
- return "";
18149
- }
18150
- function resultText(result) {
18151
- const texts = [];
18152
- if (Array.isArray(result?.content)) {
18153
- for (const part of result.content)
18154
- if (part?.type === "text" && part.text)
18155
- texts.push(part.text);
18156
- }
18157
- const line = texts.join(`
18158
- `).split(`
18159
- `).find((item) => item.trim()) ?? "";
18160
- return line.trim();
18161
- }
18162
- function compactText(member, limit) {
18163
- const extra = calls.get(member.id);
18164
- const name = member.name || extra?.name || member.id;
18165
- const arg = primaryArg(name, member.args ?? extra?.args);
18166
- const isError = member.isError || extra?.isError;
18167
- const text = resultText(member.result ?? extra?.result);
18168
- const summary = isError ? text ? "Error · " + oneLine(text, 40) : "Error" : oneLine(text, 40);
18169
- let line = arg ? name + " " + arg : name;
18170
- if (summary)
18171
- line += " · " + summary;
18172
- return wrapTextWithAnsi(line, limit);
18173
- }
18174
- function nestedLines(parentId, limit) {
18175
- const lines = [];
18176
- for (const call of calls.values()) {
18177
- if (call.parentId !== parentId || byId.has(call.id))
18178
- continue;
18179
- lines.push(...compactText(call, limit));
18180
- }
18181
- return lines;
18182
- }
18183
- function showNative(ctx, group) {
18184
- if (ctx?.expanded !== true || !group)
18185
- return false;
18186
- if (group.members.length < 2)
18187
- return true;
18188
- if (group.members[0]?.id !== ctx.toolCallId)
18189
- return true;
18190
- return group.members.every((member) => expandedById.get(member.id) === true);
18191
- }
18192
- function plainCall(name, args, width) {
18193
- const lines = wrapText(name, width);
18194
- if (args && typeof args === "object" && !Array.isArray(args)) {
18195
- for (const [key, value] of Object.entries(args)) {
18196
- const shown = typeof value === "string" ? value : JSON.stringify(value);
18197
- lines.push(...wrapText(key + ": " + shown, width));
18198
- }
18199
- } else if (args !== undefined) {
18200
- lines.push(...wrapText(JSON.stringify(args), width));
18201
- }
18202
- return lines;
18203
- }
18204
- function plainResult(result, isError, width) {
18205
- const texts = [];
18206
- if (Array.isArray(result?.content)) {
18207
- for (const part of result.content)
18208
- if (part?.type === "text" && part.text)
18209
- texts.push(part.text);
18210
- }
18211
- const lines = [];
18212
- if (isError)
18213
- lines.push(...wrapText("Error", width));
18214
- lines.push(...wrapText(texts.join(`
18215
- `), width));
18216
- return lines.filter((line) => line !== "");
18217
- }
18218
- function reset() {
18219
- open = null;
18220
- groups.length = 0;
18221
- byId.clear();
18222
- calls.clear();
18223
- expandedById.clear();
18224
- bodyGroup = new WeakMap;
18225
- }
18226
- function finish(group) {
18227
- if (!group || group.settled)
18228
- return;
18229
- group.settled = true;
18230
- for (const member of group.members)
18231
- member.isPartial = false;
18232
- ping(group.members[0]?.id);
18233
- }
18234
- function newGroup() {
18235
- open = { settled: false, expanded: false, members: [] };
18236
- groups.push(open);
18237
- return open;
18238
- }
18239
- function place(id, name, group, args) {
18240
- const current = byId.get(id);
18241
- if (current === group) {
18242
- const row = group.members.find((item) => item.id === id);
18243
- if (row && name)
18244
- row.name = name;
18245
- if (row && args !== undefined)
18246
- row.args = args;
18247
- return group;
18248
- }
18249
- if (current) {
18250
- const oldAnchor = current.members[0];
18251
- current.members = current.members.filter((item) => item.id !== id);
18252
- if (oldAnchor && oldAnchor.id !== id)
18253
- ping(oldAnchor.id);
18254
- }
18255
- const row = { id, name: name || id, isError: false, isPartial: false, args };
18256
- group.members.push(row);
18257
- byId.set(id, group);
18258
- const anchor = group.members[0];
18259
- if (anchor !== row)
18260
- ping(anchor.id);
18261
- return group;
18262
- }
18263
- function ping(id) {
18264
- if (!replaying && id)
18265
- invalidators.get(id)?.();
18266
- }
18267
- function note(message) {
18268
- if (!message || typeof message !== "object")
18269
- return;
18270
- if (message.role === "user" || message.role === "custom" && message.display) {
18271
- finish(open);
18272
- open = null;
18273
- return;
18274
- }
18275
- if (message.role === "toolResult") {
18276
- const nested = message.nestedCalls?.calls;
18277
- if (!Array.isArray(nested))
18278
- return;
18279
- for (const call of nested) {
18280
- if (!call?.id || calls.has(call.id))
18281
- continue;
18282
- remember(call.id, {
18283
- name: call.name,
18284
- args: call.arguments,
18285
- parentId: message.toolCallId,
18286
- isError: call.status === "error",
18287
- isPartial: call.status === "unfinished"
18288
- });
18289
- }
18290
- return;
18291
- }
18292
- if (message.role !== "assistant" || !Array.isArray(message.content))
18293
- return;
18294
- const toolCalls = message.content.filter((part) => part?.type === "toolCall" && part.id);
18295
- const hasBody = message.content.some((part) => part?.type === "text" && String(part.text ?? "").trim());
18296
- if (!hasBody) {
18297
- for (const call of toolCalls)
18298
- if (!byId.has(call.id))
18299
- place(call.id, call.name, open ?? newGroup(), call.arguments);
18300
- return;
18301
- }
18302
- let group = bodyGroup.get(message);
18303
- if (!group) {
18304
- if (open)
18305
- finish(open);
18306
- group = newGroup();
18307
- bodyGroup.set(message, group);
18308
- }
18309
- for (const call of toolCalls)
18310
- place(call.id, call.name, group, call.arguments);
18311
- }
18312
- function remember(id, fields) {
18313
- let row = calls.get(id);
18314
- if (!row) {
18315
- row = { id, name: "", isError: false, isPartial: false };
18316
- calls.set(id, row);
18317
- }
18318
- if (fields.name)
18319
- row.name = fields.name;
18320
- if (fields.args !== undefined)
18321
- row.args = fields.args;
18322
- if (fields.parentId)
18323
- row.parentId = fields.parentId;
18324
- if (fields.isError !== undefined)
18325
- row.isError = fields.isError;
18326
- if (fields.isPartial !== undefined)
18327
- row.isPartial = fields.isPartial;
18328
- if (fields.result !== undefined)
18329
- row.result = fields.result;
18330
- const owner = byId.get(row.parentId || id);
18331
- ping(owner?.members[0]?.id);
18332
- return row;
18333
- }
18334
- function pathPart(verb, one, many, ops) {
18335
- if (!ops.length)
18336
- return;
18337
- const paths = [];
18338
- for (const op of ops) {
18339
- const path = op.args && typeof op.args === "object" ? op.args.path ?? op.args.file_path : undefined;
18340
- if (typeof path !== "string" || !path)
18341
- return verb + " " + ops.length;
18342
- paths.push(path);
18343
- }
18344
- const count = new Set(paths).size;
18345
- return verb + " " + count + " " + (count === 1 ? one : many);
18346
- }
18347
- function times(n, one, many) {
18348
- return "Ran " + n + " " + (n === 1 ? one : many);
18349
- }
18350
- function summarize(group) {
18351
- const seen = new Map;
18352
- for (const member of group.members) {
18353
- const extra = calls.get(member.id);
18354
- seen.set(member.id, {
18355
- name: member.name || extra?.name,
18356
- args: member.args ?? extra?.args,
18357
- isError: member.isError || extra?.isError,
18358
- isPartial: member.isPartial || extra?.isPartial
18359
- });
18360
- }
18361
- for (const call of calls.values()) {
18362
- if (!call.parentId || !seen.has(call.parentId) || seen.has(call.id))
18363
- continue;
18364
- seen.set(call.id, call);
18365
- }
18366
- const all = [...seen.values()];
18367
- const named = (name) => all.filter((item) => item.name === name);
18368
- const parts = [];
18369
- const code = named("codemode");
18370
- if (code.length)
18371
- parts.push("Ran " + code.length + " codemode");
18372
- const read = pathPart("Read", "file", "files", named("read"));
18373
- if (read)
18374
- parts.push(read);
18375
- const write = pathPart("Wrote", "file", "files", named("write"));
18376
- if (write)
18377
- parts.push(write);
18378
- const edit = pathPart("Edited", "file", "files", named("edit"));
18379
- if (edit)
18380
- parts.push(edit);
18381
- const shell = named("bash").length + named("powershell").length;
18382
- if (shell)
18383
- parts.push(times(shell, "shell command", "shell commands"));
18384
- const grep = named("grep").length;
18385
- if (grep)
18386
- parts.push(times(grep, "content search", "content searches"));
18387
- const find = named("find").length;
18388
- if (find)
18389
- parts.push(times(find, "file search", "file searches"));
18390
- const listed = pathPart("Listed", "directory", "directories", named("ls"));
18391
- if (listed)
18392
- parts.push(listed);
18393
- const search = named("tool_search").length;
18394
- if (search)
18395
- parts.push(times(search, "tool search", "tool searches"));
18396
- const known = new Set([
18397
- "codemode",
18398
- "read",
18399
- "write",
18400
- "edit",
18401
- "bash",
18402
- "powershell",
18403
- "grep",
18404
- "find",
18405
- "ls",
18406
- "tool_search"
18407
- ]);
18408
- const other = all.filter((item) => item.name && !known.has(item.name)).length;
18409
- if (other)
18410
- parts.push(times(other, "other tool call", "other tool calls"));
18411
- const failed = all.filter((item) => item.isError).length;
18412
- if (failed)
18413
- parts.push(failed + " failed");
18414
- return parts.length ? parts : [group.members.length + " tools"];
18415
- }
18416
- function callPath(args) {
18417
- const path = args && typeof args === "object" ? args.path ?? args.file_path : undefined;
18418
- return typeof path === "string" && path ? path : undefined;
18419
- }
18420
- function activity(call) {
18421
- const path = callPath(call.args);
18422
- if (call.name === "read")
18423
- return path ? "Reading " + path + "…" : "Reading…";
18424
- if (call.name === "write")
18425
- return path ? "Writing " + path + "…" : "Writing…";
18426
- if (call.name === "edit")
18427
- return path ? "Editing " + path + "…" : "Editing…";
18428
- if (call.name === "ls")
18429
- return path ? "Listing " + path + "…" : "Listing…";
18430
- if (call.name)
18431
- return "Running " + call.name + "…";
18432
- return "Working…";
18433
- }
18434
- function belongs(call, memberIds) {
18435
- let current = call;
18436
- const seen = new Set;
18437
- while (current && !seen.has(current.id)) {
18438
- if (memberIds.has(current.id))
18439
- return true;
18440
- seen.add(current.id);
18441
- current = current.parentId ? calls.get(current.parentId) : undefined;
18442
- }
18443
- return false;
18444
- }
18445
- function header(group) {
18446
- if (!runActive || group.settled)
18447
- return summarize(group);
18448
- const memberIds = new Set(group.members.map((member) => member.id));
18449
- const partial = [];
18450
- for (const member of group.members) {
18451
- const extra = calls.get(member.id);
18452
- if (member.isPartial || extra?.isPartial)
18453
- partial.push(Object.assign({ id: member.id }, member, extra || {}));
18454
- }
18455
- for (const call of calls.values()) {
18456
- if (!call.isPartial || partial.some((item) => item.id === call.id))
18457
- continue;
18458
- if (belongs(call, memberIds))
18459
- partial.push(call);
18460
- }
18461
- const covered = new Set;
18462
- for (const call of partial) {
18463
- let parent = call.parentId;
18464
- while (parent) {
18465
- covered.add(parent);
18466
- parent = calls.get(parent)?.parentId;
18467
- }
18468
- }
18469
- const parts = partial.filter((call) => !covered.has(call.id)).map(activity);
18470
- if (!parts.length)
18471
- parts.push("Working…");
18472
- const failed = summarize(group).filter((part) => part.endsWith(" failed"));
18473
- return parts.concat(failed);
18474
- }
18475
- function fit(parts, width) {
18476
- const limit = Math.max(1, width || 1);
18477
- const lines = [];
18478
- let line = "";
18479
- for (const part of parts) {
18480
- const piece = truncateToWidth(part, limit, "");
18481
- const next = line ? line + " · " + piece : piece;
18482
- if (line && visibleWidth(next) > limit) {
18483
- lines.push(line);
18484
- line = piece;
18485
- } else {
18486
- line = next;
18487
- }
18488
- }
18489
- if (line)
18490
- lines.push(line);
18491
- return lines;
18492
- }
18493
- function visibleEntries(ctx) {
18494
- const build = ctx?.sessionManager?.buildContextEntries;
18495
- if (typeof build !== "function")
18496
- return;
18497
- const entries = build.call(ctx.sessionManager);
18498
- return Array.isArray(entries) ? entries : undefined;
18499
- }
18500
- function replay(ctx) {
18501
- const entries = visibleEntries(ctx);
18502
- if (!entries)
18503
- return;
18504
- replaying = true;
18505
- reset();
18506
- for (const entry of entries) {
18507
- if (entry?.type === "message")
18508
- note(entry.message);
18509
- else if (entry?.type === "custom_message")
18510
- note({ role: "custom", display: entry.display });
18511
- }
18512
- replaying = false;
18513
- for (const id of invalidators.keys())
18514
- if (!byId.has(id))
18515
- invalidators.delete(id);
18516
- for (const invalidate of invalidators.values())
18517
- invalidate();
18518
- }
18519
- function stopRun() {
18520
- runActive = false;
18521
- for (const call of calls.values())
18522
- call.isPartial = false;
18523
- for (const group of groups)
18524
- for (const member of group.members)
18525
- member.isPartial = false;
18526
- finish(open);
18527
- for (const invalidate of invalidators.values())
18528
- invalidate();
18529
- }
18530
- let unwatch = null;
18531
- function watch(manager) {
18532
- unwatch?.();
18533
- unwatch = null;
18534
- const original = manager?.appendCustomMessageEntry;
18535
- if (typeof original !== "function")
18536
- return;
18537
- const own = Object.getOwnPropertyDescriptor(manager, "appendCustomMessageEntry");
18538
- let active = true;
18539
- const wrapper = function(...args) {
18540
- const id = original.apply(this, args);
18541
- if (active)
18542
- note({ role: "custom", display: args[2] });
18543
- return id;
18544
- };
18545
- try {
18546
- manager.appendCustomMessageEntry = wrapper;
18547
- } catch {
18548
- return;
18549
- }
18550
- unwatch = () => {
18551
- active = false;
18552
- if (manager.appendCustomMessageEntry !== wrapper)
18553
- return;
18554
- if (own)
18555
- Object.defineProperty(manager, "appendCustomMessageEntry", own);
18556
- else
18557
- delete manager.appendCustomMessageEntry;
18558
- };
18559
- }
18560
- pi.on("session_start", (_event, ctx) => {
18561
- runActive = false;
18562
- watch(ctx?.sessionManager);
18563
- replay(ctx);
18564
- });
18565
- pi.on("session_shutdown", () => {
18566
- unwatch?.();
18567
- unwatch = null;
18568
- });
18569
- pi.on("session_compact", (_event, ctx) => replay(ctx));
18570
- pi.on("session_tree", (_event, ctx) => replay(ctx));
18571
- pi.on("agent_start", () => {
18572
- runActive = true;
18573
- });
18574
- pi.on("agent_end", () => stopRun());
18575
- pi.on("message_start", (event) => note(event?.message));
18576
- pi.on("message_update", (event) => note(event?.message));
18577
- pi.on("tool_execution_start", (event) => {
18578
- if (!event?.toolCallId)
18579
- return;
18580
- runActive = true;
18581
- remember(event.toolCallId, {
18582
- name: event.toolName,
18583
- args: event.args,
18584
- parentId: event.parentToolCallId,
18585
- isPartial: true
18586
- });
18587
- });
18588
- pi.on("tool_execution_end", (event) => {
18589
- if (!event?.toolCallId)
18590
- return;
18591
- remember(event.toolCallId, {
18592
- name: event.toolName,
18593
- args: event.args,
18594
- parentId: event.parentToolCallId,
18595
- isError: event.isError === true,
18596
- isPartial: false,
18597
- result: event.result
18598
- });
18599
- });
18600
- pi.registerToolRenderer((toolName, next) => {
18601
- const later = next();
18602
- if (later?.isVibestToolGroups === true)
18603
- return later;
18604
- return {
18605
- isVibestToolGroups: true,
18606
- renderShell: "self",
18607
- renderCall(args, theme, ctx) {
18608
- if (ctx?.toolCallId)
18609
- expandedById.set(ctx.toolCallId, ctx.expanded === true);
18610
- if (ctx?.invalidate)
18611
- invalidators.set(ctx.toolCallId, ctx.invalidate);
18612
- let group = byId.get(ctx.toolCallId);
18613
- if (!group)
18614
- group = place(ctx.toolCallId, toolName, open ?? newGroup(), args);
18615
- const row = group.members.find((item) => item.id === ctx.toolCallId);
18616
- if (row) {
18617
- row.name = toolName;
18618
- if (args !== undefined)
18619
- row.args = args;
18620
- }
18621
- const renderers = (() => {
18622
- try {
18623
- return next();
18624
- } catch {
18625
- return;
18626
- }
18627
- })();
18628
- let native;
18629
- if (renderers?.renderCall) {
18630
- try {
18631
- native = renderers.renderCall(args, theme, {
18632
- ...ctx,
18633
- expanded: true,
18634
- lastComponent: ctx.lastComponent?.native
18635
- });
18636
- } catch {
18637
- native = undefined;
18638
- }
18639
- }
18640
- const body = native ? frameComponent(renderers, native, ctx.outputPad) : {
18641
- render(innerWidth) {
18642
- const { pad, limit } = gutter(innerWidth, ctx.outputPad);
18643
- return indent(plainCall(toolName, args, limit), pad);
18644
- }
18645
- };
18646
- return {
18647
- native,
18648
- invalidate() {
18649
- native?.invalidate?.();
18650
- },
18651
- render(width) {
18652
- const current = byId.get(ctx.toolCallId);
18653
- if (!current)
18654
- return [];
18655
- const isAnchor = current.members[0]?.id === ctx.toolCallId;
18656
- if (isAnchor && ctx.expanded !== current.expanded) {
18657
- current.expanded = ctx.expanded;
18658
- const ids = current.members.map((member) => member.id);
18659
- queueMicrotask(() => {
18660
- for (const id of ids)
18661
- if (id !== ctx.toolCallId)
18662
- invalidators.get(id)?.();
18663
- });
18664
- }
18665
- const { pad, limit } = gutter(width, ctx.outputPad);
18666
- const paint = (line) => typeof theme?.fg === "function" ? theme.fg("muted", line) : line;
18667
- const title = indent(fit(header(current), limit).map(paint), pad);
18668
- if (!current.expanded)
18669
- return isAnchor ? title : [];
18670
- if (showNative(ctx, current))
18671
- return isAnchor ? [...title, ...body.render(width)] : body.render(width);
18672
- const row = current.members.find((item) => item.id === ctx.toolCallId);
18673
- const lines = indent(compactText(row, limit), pad);
18674
- if (isAnchor)
18675
- lines.unshift(...title);
18676
- lines.push(...indent(nestedLines(ctx.toolCallId, limit), pad));
18677
- return lines;
18678
- }
18679
- };
18680
- },
18681
- renderResult(result, options, theme, ctx) {
18682
- if (ctx?.toolCallId)
18683
- expandedById.set(ctx.toolCallId, ctx.expanded === true);
18684
- const group = byId.get(ctx.toolCallId) ?? place(ctx.toolCallId, toolName, open ?? newGroup());
18685
- const row = group.members.find((item) => item.id === ctx.toolCallId);
18686
- const changed = row.result !== result || row.isError !== ctx.isError || row.isPartial !== ctx.isPartial;
18687
- row.result = result;
18688
- row.isError = ctx.isError;
18689
- row.isPartial = ctx.isPartial;
18690
- if (row !== group.members[0] && changed)
18691
- ping(group.members[0]?.id);
18692
- const renderers = (() => {
18693
- try {
18694
- return next();
18695
- } catch {
18696
- return;
18697
- }
18698
- })();
18699
- let native;
18700
- if (renderers?.renderResult) {
18701
- try {
18702
- native = renderers.renderResult(result, { ...options, expanded: true }, theme, {
18703
- ...ctx,
18704
- lastComponent: ctx.lastComponent?.native
18705
- });
18706
- } catch {
18707
- native = undefined;
18708
- }
18709
- }
18710
- const body = native ? frameComponent(renderers, native, ctx.outputPad) : {
18711
- render(innerWidth) {
18712
- const { pad, limit } = gutter(innerWidth, ctx.outputPad);
18713
- return indent(plainResult(result, ctx.isError, limit), pad);
18714
- }
18715
- };
18716
- return {
18717
- native,
18718
- invalidate() {
18719
- native?.invalidate?.();
18720
- },
18721
- render(width) {
18722
- const current = byId.get(ctx.toolCallId);
18723
- if (!current?.expanded || !showNative(ctx, current))
18724
- return [];
18725
- return body.render(width);
18726
- }
18727
- };
18728
- }
18729
- };
18730
- });
18731
- }
18732
-
18733
- // src/tui/user-message-padding.ts
18734
- import { UserMessageComponent } from "@earendil-works/pi-coding-agent";
18735
- import { TuiAltScreen } from "@earendil-works/pi-tui";
18736
- function readLease(proto) {
18737
- const lease = Object.getOwnPropertyDescriptor(proto, "vibestCompactUserMessagesLease")?.value;
18738
- return lease?.by === compactUserMessages ? lease : undefined;
18739
- }
18740
- function writeLease(proto, lease) {
18741
- if (lease)
18742
- Object.defineProperty(proto, "vibestCompactUserMessagesLease", {
18743
- value: lease,
18744
- configurable: true,
18745
- enumerable: false,
18746
- writable: false
18747
- });
18748
- else
18749
- delete proto.vibestCompactUserMessagesLease;
18750
- }
18751
- function restoreRender(child, descriptor) {
18752
- if (descriptor)
18753
- Object.defineProperty(child, "render", descriptor);
18754
- else
18755
- delete child.render;
18756
- }
18757
- function compact(original, width) {
18758
- const ZONE_A = "\x1B]133;A\x07";
18759
- const ZONE_B = "\x1B]133;B\x07";
18760
- const ZONE_C = "\x1B]133;C\x07";
18761
- const INVERTED = ZONE_B + ZONE_C + ZONE_A;
18762
- const LEADING = ZONE_A + ZONE_B + ZONE_C;
18763
- const children = this.children;
18764
- const restores = [];
18765
- try {
18766
- if (Array.isArray(children)) {
18767
- for (const child of children) {
18768
- if (!child || typeof child !== "object")
18769
- continue;
18770
- const view = child;
18771
- const paddingY = view.paddingY;
18772
- if (!Number.isInteger(paddingY) || paddingY <= 0 || typeof view.render !== "function")
18773
- continue;
18774
- const descriptor = Object.getOwnPropertyDescriptor(view, "render");
18775
- const childRender = view.render;
18776
- view.render = function(innerWidth) {
18777
- const lines = childRender.call(this, innerWidth);
18778
- if (!Array.isArray(lines) || lines.length <= paddingY * 2)
18779
- return lines;
18780
- return lines.slice(paddingY, lines.length - paddingY);
18781
- };
18782
- restores.push(() => restoreRender(view, descriptor));
18783
- }
18784
- }
18785
- const lines = original.call(this, width);
18786
- if (!Array.isArray(lines) || lines.length !== 1 || typeof lines[0] !== "string" || !lines[0].startsWith(INVERTED))
18787
- return lines;
18788
- const copy = lines.slice();
18789
- copy[0] = LEADING + lines[0].slice(INVERTED.length);
18790
- return copy;
18791
- } finally {
18792
- for (let i = restores.length - 1;i >= 0; i--)
18793
- restores[i]();
18794
- }
18795
- }
18796
- function isFramePaint(paint, lease, nativePaint) {
18797
- if (typeof paint !== "function")
18798
- return false;
18799
- if (lease?.paint === paint || nativePaint === paint)
18800
- return true;
18801
- return paint.toString().includes("renderLayoutFrame");
18802
- }
18803
- function compactUserMessages(pi) {
18804
- const owner = {};
18805
- let nativeRender;
18806
- let nativePaint;
18807
- let release = null;
18808
- function install() {
18809
- const message = UserMessageComponent?.prototype;
18810
- const alt = TuiAltScreen?.prototype;
18811
- const render = message?.render;
18812
- const paint = alt?.doRender;
18813
- if (!message || !alt || typeof render !== "function")
18814
- return () => {};
18815
- let lease = readLease(message);
18816
- if (!isFramePaint(paint, lease, nativePaint))
18817
- return () => {};
18818
- if (lease)
18819
- lease.owners.add(owner);
18820
- else if ((nativeRender === undefined || render === nativeRender) && (nativePaint === undefined || paint === nativePaint)) {
18821
- let framing = false;
18822
- const next = {
18823
- by: compactUserMessages,
18824
- owners: new Set([owner]),
18825
- render(width) {
18826
- if (!next.active || !framing)
18827
- return render.call(this, width);
18828
- return compact.call(this, render, width);
18829
- },
18830
- paint() {
18831
- if (!next.active)
18832
- return paint.call(this);
18833
- framing = true;
18834
- try {
18835
- return paint.call(this);
18836
- } finally {
18837
- framing = false;
18838
- }
18839
- },
18840
- renderOriginal: render,
18841
- paintOriginal: paint,
18842
- active: true
18843
- };
18844
- writeLease(message, next);
18845
- try {
18846
- message.render = next.render;
18847
- } catch (error) {
18848
- writeLease(message, undefined);
18849
- throw error;
18850
- }
18851
- try {
18852
- alt.doRender = next.paint;
18853
- } catch (error) {
18854
- message.render = render;
18855
- writeLease(message, undefined);
18856
- throw error;
18857
- }
18858
- lease = next;
18859
- } else
18860
- return () => {};
18861
- const held = lease;
18862
- nativeRender = held.renderOriginal;
18863
- nativePaint = held.paintOriginal;
18864
- let released = false;
18865
- return () => {
18866
- if (released)
18867
- return;
18868
- released = true;
18869
- held.owners.delete(owner);
18870
- if (held.owners.size > 0)
18871
- return;
18872
- held.active = false;
18873
- if (message.render === held.render)
18874
- message.render = held.renderOriginal;
18875
- if (alt.doRender === held.paint)
18876
- alt.doRender = held.paintOriginal;
18877
- if (readLease(message) === held)
18878
- writeLease(message, undefined);
18879
- };
18880
- }
18881
- pi.on("session_start", (_event, ctx) => {
18882
- if (ctx?.mode !== "tui" || !ctx.hasUI) {
18883
- release?.();
18884
- release = null;
18885
- return;
18886
- }
18887
- release?.();
18888
- release = install();
18889
- });
18890
- pi.on("session_shutdown", () => {
18891
- release?.();
18892
- release = null;
18893
- });
18894
- }
18414
+ // src/version.ts
18415
+ var VERSION = "0.0.1-beta.20";
18895
18416
 
18896
18417
  // src/extension.ts
18418
+ var { withVibest: withVibest2 } = makeClient({ version: VERSION });
18897
18419
  var skillsDir = path.join(path.dirname(url.fileURLToPath(import.meta.url)), "skills");
18898
18420
  var encodeJson = encodeSync(fromJsonString2(Unknown2));
18899
- var COORDINATOR = "coordinator";
18900
- var guarded = (agent, sessionId) => gen2(function* () {
18421
+ var decodeRefusal = decodeUnknownOption2(String4);
18422
+ var decodeVibestDetails = decodeUnknownOption2(Struct({ execution: Number5 }));
18423
+ var guarded = (sessionId) => gen2(function* () {
18901
18424
  const pi = yield* Pi;
18902
18425
  const layout = yield* Layout;
18903
18426
  yield* pi.handle("tool_call", (e, ctx) => gen2(function* () {
18904
- const headers = yield* claimHeaders(sessionId ? { _tag: "session", sessionId, pluginVersion: VERSION } : { _tag: "cli", repositoryRoot: ctx.cwd });
18427
+ const headers = yield* claimHeaders(Claim.session({ sessionId, pluginVersion: VERSION }));
18905
18428
  const input = encodeJson({ tool_name: e.toolName, tool_input: e.input, cwd: ctx.cwd });
18906
- const exit = yield* hookCall(layout.socket, headers, (client) => client["Integration.Guard"]({ harness: "pi", agent, input }));
18429
+ const exit = yield* hookCall(layout.socket, headers, (client) => client["Integration.Guard"]({ harness: "pi", input }));
18907
18430
  if (isFailure3(exit))
18908
18431
  return {
18909
18432
  block: true,
18910
18433
  reason: `vibest could not check this tool call (${pretty(exit.cause)}); it is refused.`
18911
18434
  };
18912
- const reason = exit.value.answer;
18913
- return typeof reason === "string" && reason ? { block: true, reason } : undefined;
18435
+ const reason = decodeRefusal(exit.value.answer);
18436
+ return isSome2(reason) && reason.value ? { block: true, reason: reason.value } : undefined;
18914
18437
  }));
18915
18438
  });
18916
18439
  var lastReply = (messages) => {
@@ -18918,23 +18441,34 @@ var lastReply = (messages) => {
18918
18441
  const text = (message?.content ?? []).flatMap((c) => c.type === "text" ? [c.text] : []).join("");
18919
18442
  return { text, error: message?.stopReason === "error" ? message.errorMessage || "error" : "" };
18920
18443
  };
18921
- var piHeaders = (sessionId, ctx) => claimHeaders({
18922
- _tag: "session",
18444
+ var piHeaders = (sessionId, ctx, current) => claimHeaders(Claim.session({
18923
18445
  sessionId,
18924
18446
  harnessSessionId: ctx.sessionManager.getSessionId(),
18925
- pluginVersion: VERSION
18926
- });
18927
- var session = (sessionId) => effectDiscard(gen2(function* () {
18447
+ pluginVersion: VERSION,
18448
+ ...current !== undefined && { process: current }
18449
+ }));
18450
+ var session = (sessionId, processId) => effectDiscard(gen2(function* () {
18928
18451
  const pi = yield* Pi;
18929
18452
  const layout = yield* Layout;
18930
18453
  const root = yield* make24(false);
18931
18454
  const reply = yield* make24({ text: "", error: "" });
18932
18455
  yield* pi.handle("session_start", (_e, ctx) => set2(root, ctx.mode === "tui"));
18933
18456
  yield* pi.handle("agent_end", (e) => set2(reply, lastReply(e.messages)));
18457
+ yield* pi.handle("message_start", (e, ctx) => gen2(function* () {
18458
+ const message = e.message;
18459
+ if (message.role !== "custom" || message.customType !== "vibest")
18460
+ return;
18461
+ const details = decodeVibestDetails(message.details);
18462
+ if (isNone2(details))
18463
+ return;
18464
+ const headers = yield* piHeaders(sessionId, ctx, yield* get2(processId));
18465
+ const event = encodeJson({ type: "accepted", execution: details.value.execution });
18466
+ yield* hookCall(layout.socket, headers, (client) => client.Prompt({ sessionId, harness: "pi", event }));
18467
+ }));
18934
18468
  yield* pi.handle("input", (e, ctx) => gen2(function* () {
18935
18469
  if (e.source === "extension" || e.text.trim() === "")
18936
18470
  return;
18937
- const headers = yield* piHeaders(sessionId, ctx);
18471
+ const headers = yield* piHeaders(sessionId, ctx, yield* get2(processId));
18938
18472
  const event = encodeJson({ type: "input", text: e.text, source: e.source });
18939
18473
  yield* hookCall(layout.socket, headers, (client) => client.Prompt({ sessionId, harness: "pi", event }));
18940
18474
  }));
@@ -18942,9 +18476,9 @@ var session = (sessionId) => effectDiscard(gen2(function* () {
18942
18476
  if (!(yield* get2(root)) || !ctx.isIdle())
18943
18477
  return;
18944
18478
  const { text, error } = yield* get2(reply);
18945
- const headers = yield* piHeaders(sessionId, ctx);
18479
+ const headers = yield* piHeaders(sessionId, ctx, yield* get2(processId));
18946
18480
  const event = encodeJson({ type: "agent_settled", text, error, aborted: e.aborted });
18947
- yield* hookCall(layout.socket, headers, (client) => client.TurnEnd({ sessionId, harness: "pi", event }));
18481
+ yield* hookCall(layout.socket, headers, (client) => client.ExecutionEnd({ sessionId, harness: "pi", event }));
18948
18482
  }));
18949
18483
  }));
18950
18484
  var reportSession = fn2("reportSession")(function* (sessionId) {
@@ -18957,57 +18491,65 @@ var reportSession = fn2("reportSession")(function* (sessionId) {
18957
18491
  if (ctx.mode !== "tui" || (yield* get2(reported)) === harnessSessionId)
18958
18492
  return;
18959
18493
  const headers = yield* piHeaders(sessionId, ctx);
18960
- yield* connect2(layout.socket).pipe(flatMap4((client) => client.CoordinatorSessionReady({ sessionId, harness: "pi", harnessSessionId }, { headers })), scoped2, timeout2("1 second"), andThen2(set2(reported, harnessSessionId)), catchCause2((cause) => hasInterruptsOnly2(cause) ? void_3 : sync2(() => ctx.ui.notify(`vibest: the coordinator's conversation may not have been saved: ${pretty(cause)}`, "warning"))), forkIn2(scope));
18494
+ yield* connect2(layout.socket).pipe(flatMap4((client) => client["Session.Ready"]({ id: sessionId, conversation: { harness: "pi", id: harnessSessionId } }, { headers })), scoped2, timeout2("1 second"), andThen2(set2(reported, harnessSessionId)), catchCause2((cause) => hasInterruptsOnly2(cause) ? void_3 : sync2(() => ctx.ui.notify(`vibest: the entry session's conversation may not have been saved: ${pretty(cause)}`, "warning"))), forkIn2(scope));
18961
18495
  });
18962
18496
  yield* pi.handle("session_start", (event, ctx) => event.reason === "new" || event.reason === "resume" || event.reason === "fork" ? send(ctx) : void_3);
18963
18497
  yield* pi.handle("agent_end", (_event, ctx) => send(ctx));
18964
18498
  });
18965
- var coordinator = effectDiscard(gen2(function* () {
18499
+ var terminal = (sessionId) => effectDiscard(gen2(function* () {
18966
18500
  const pi = yield* Pi;
18967
18501
  yield* pi.handle("resources_discover", () => succeed7({ skillPaths: [skillsDir] }));
18968
- yield* pi.handle("before_agent_start", (e) => sync2(() => {
18969
- e.systemPromptOptions.sections = {};
18970
- }));
18971
- yield* pi.load(tool_groups_default);
18972
- yield* pi.load(compactUserMessages);
18973
- const sessionId = yield* option3(String5("VIBEST_SESSION_ID"));
18974
- if (isNone2(sessionId))
18975
- return;
18976
- yield* reportSession(sessionId.value);
18502
+ yield* reportSession(sessionId);
18503
+ }));
18504
+ var inbox = (sessionId, processId) => effectDiscard(gen2(function* () {
18505
+ const pi = yield* Pi;
18977
18506
  const started = yield* make5();
18978
18507
  yield* pi.handle("session_start", (_e, ctx) => ctx.mode === "tui" ? succeed4(started, ctx).pipe(asVoid2) : void_3);
18979
- const subscribe = (ctx) => withVibest({
18980
- _tag: "session",
18981
- sessionId: sessionId.value,
18508
+ const identity = (ctx) => map6(get2(processId), (current) => Claim.session({
18509
+ sessionId,
18982
18510
  harnessSessionId: ctx.sessionManager.getSessionId(),
18983
- pluginVersion: VERSION
18984
- }, (client) => client["Inbox.Subscribe"](undefined).pipe(runForEach2((content) => pi.sendMessage({ customType: "vibest", content, display: false }, { triggerTurn: true, deliverAs: "followUp" })), catchCause2((cause) => hasInterruptsOnly2(cause) ? void_3 : failCause3(cause))), { start: false }).pipe(retry2({
18985
- while: (e) => e._tag === "RpcClientError" || e._tag === "DaemonUnavailable",
18511
+ pluginVersion: VERSION,
18512
+ ...current !== undefined && { process: current }
18513
+ }));
18514
+ const takeNext = (ctx) => gen2(function* () {
18515
+ if (!ctx.isIdle())
18516
+ return;
18517
+ const taken = yield* withVibest2(yield* identity(ctx), (client) => client["Inbox.Take"](undefined), {
18518
+ start: false
18519
+ });
18520
+ if (taken === null)
18521
+ return;
18522
+ yield* pi.sendMessage({ customType: "vibest", content: taken.text, display: false, details: { execution: taken.execution } }, { triggerTurn: true });
18523
+ }).pipe(ignore2);
18524
+ yield* pi.handle("agent_settled", (_e, ctx) => takeNext(ctx));
18525
+ const subscribe = (ctx) => flatMap4(identity(ctx), (who) => withVibest2(who, (client) => client["Inbox.Subscribe"](undefined).pipe(runForEach2(() => takeNext(ctx)), catchCause2((cause) => hasInterruptsOnly2(cause) ? void_3 : failCause3(cause))), { start: false })).pipe(retry2({
18526
+ while: (e) => isTagged(e, "RpcClientError") || isTagged(e, "DaemonUnavailable"),
18986
18527
  schedule: spaced("2 seconds")
18987
18528
  }), repeat2(spaced("2 seconds")));
18988
18529
  yield* _await(started).pipe(flatMap4((ctx) => subscribe(ctx).pipe(catchCause2((cause) => hasInterruptsOnly2(cause) ? void_3 : sync2(() => ctx.ui.notify(`vibest: inbox subscription ended: ${pretty(cause)}`, "error"))))), forkScoped2);
18989
18530
  }));
18990
- var ready = (sessionId) => effectDiscard(gen2(function* () {
18531
+ var ready = (sessionId, processId) => effectDiscard(gen2(function* () {
18991
18532
  const pi = yield* Pi;
18992
18533
  const scope = yield* scope2;
18993
- yield* pi.handle("session_start", (_e, ctx) => ctx.mode !== "tui" ? void_3 : withVibest({ _tag: "session", sessionId, pluginVersion: VERSION }, (client) => client["Session.Ready"]({ id: sessionId, pid: process.pid }), { start: false }).pipe(timeout2("2 seconds"), retry2({
18994
- while: (e) => e._tag === "DaemonUnavailable" || e._tag === "RpcClientError" || e._tag === "TimeoutError",
18534
+ yield* pi.handle("session_start", (_e, ctx) => ctx.mode !== "tui" ? void_3 : get2(processId).pipe(flatMap4((current) => withVibest2(Claim.session({
18535
+ sessionId,
18536
+ pluginVersion: VERSION,
18537
+ ...current !== undefined && { process: current }
18538
+ }), (client) => client["Session.Ready"]({ id: sessionId, pid: process.pid }), { start: false })), tap2((answer) => answer.process === undefined ? void_3 : set2(processId, String(answer.process))), timeout2("2 seconds"), retry2({
18539
+ while: (e) => isTagged(e, "DaemonUnavailable") || isTagged(e, "RpcClientError") || isTagged(e, "TimeoutError"),
18995
18540
  schedule: spaced("1 second")
18996
18541
  }), ignore2, forkIn2(scope), asVoid2));
18997
18542
  }));
18998
18543
  var extension2 = unwrap(gen2(function* () {
18999
- const agent = getOrUndefined(yield* option3(String5("VIBEST_AGENT")));
19000
- if (!agent)
19001
- return empty4;
19002
18544
  const sessionId = getOrUndefined(yield* option3(String5("VIBEST_SESSION_ID")));
19003
- const guarding = effectDiscard(guarded(agent, sessionId));
19004
- const guard = sessionId ? merge2(guarding, ready(sessionId)) : guarding;
19005
- if (agent === COORDINATOR)
19006
- return coordinator.pipe(provideMerge(guard));
19007
- return sessionId ? session(sessionId).pipe(provideMerge(guard)) : guard;
18545
+ if (!sessionId)
18546
+ return empty4;
18547
+ const processId = yield* make24(getOrUndefined(yield* option3(String5("VIBEST_PROCESS"))));
18548
+ const guard = merge2(effectDiscard(guarded(sessionId)), ready(sessionId, processId));
18549
+ return terminal(sessionId).pipe(provideMerge(mergeAll2(session(sessionId, processId), inbox(sessionId, processId)).pipe(provideMerge(guard))));
19008
18550
  }));
19009
18551
  var vibestCommand = effect(VibestCommand, schema(fromJsonString2(ArraySchema(String4)), "VIBEST_COMMAND").pipe(withDefault3(["vibest"])));
19010
- var services = mergeAll2(Layout.layer, layer.pipe(provide2(layer2)), layer2, succeed6(SocketConnector, (endpoint) => makeNet({ path: endpoint })), vibestCommand).pipe(provideMerge(layer3));
18552
+ var services = mergeAll2(Layout.layer, layer.pipe(provide2(layer2)), layer2, succeed6(Service3, (endpoint) => makeNet({ path: endpoint })), vibestCommand).pipe(provideMerge(layer3));
19011
18553
  var extension_default = (api) => Pi.runMain(api, extension2.pipe(provide2(services)));
19012
18554
  export {
19013
18555
  extension_default as default,