@miadi/tide 0.6.7 → 0.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.6.7",
3
+ "version": "0.6.9",
4
4
  "description": "Typed client boundary for the ironsilk `tide` runtime. Daemon Unix-socket transport with CLI fallback.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -17,7 +17,7 @@
17
17
  "scripts/*.py"
18
18
  ],
19
19
  "dependencies": {
20
- "@miadi/annotate-core": "^0.3.1",
20
+ "@miadi/annotate-core": "^0.5.0",
21
21
  "@miadi/tide-contract": "0.3.5"
22
22
  },
23
23
  "keywords": [
@@ -63,6 +63,17 @@ else
63
63
  fi
64
64
 
65
65
  # Extract the region BETWEEN the last two horizontal rules.
66
+ if printf '%s\n' "$PANE" | grep -q '^›'; then
67
+ # Codex has no horizontal-rule composer. Its last › row is the live input;
68
+ # the native placeholder proves emptiness. Blank/unknown prompts stay held.
69
+ INPUT=$(printf '%s\n' "$PANE" | awk '/^›/ { input = $0 } END { print input }' \
70
+ | sed 's/^›[[:space:]]*//; s/[[:space:]]*$//')
71
+ if [ "$INPUT" = 'Ask Codex to do anything' ]; then
72
+ INPUT=''
73
+ elif [ -z "$INPUT" ]; then
74
+ INPUT='Codex composer has no visible empty-input placeholder'
75
+ fi
76
+ else
66
77
  INPUT=$(printf '%s\n' "$PANE" | awk '
67
78
  { line[NR] = $0; if ($0 ~ /[─━]{10,}/) rule[++r] = NR }
68
79
  END {
@@ -76,6 +87,7 @@ INPUT=$(printf '%s\n' "$PANE" | awk '
76
87
  | grep -viE 'bypass permissions|esc to interrupt|shift\+tab|for agents|^/rc$|ctrl\+' \
77
88
  | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' \
78
89
  | grep -v '^$')
90
+ fi
79
91
 
80
92
  if [ -n "$INPUT" ]; then
81
93
  say "COMPOSING $TARGET has text at its prompt — someone is writing."
package/src/annotate.ts CHANGED
@@ -626,22 +626,12 @@ function assertTarget(target: string): void {
626
626
 
627
627
  // -------------------------------------------------------------------- verbs --
628
628
 
629
- /**
630
- * The newest earlier vessel that holds this very reply from this very pane and
631
- * has marks on it. Fetching reopens it instead of keeping a fresh copy, so
632
- * marks another person made on the reply are there when it is fetched again
633
- * (Episode 339: William opens an agent in the cockpit and finds Mia's marks).
634
- * Two layouts are searched: web runs at `<root>/web/<run>/<vessel>/` and
635
- * terminal `tan` runs at `<root>/<stamp>-<target>/`, which the review script
636
- * gives a `source.json` since jgwill/gaia#87. Their stamps are not comparable
637
- * (UTC vs local time), so matches are ordered by `fetched_at`.
638
- * Null when the reply changed since, or nobody marked it.
639
- */
640
- export async function findMarkedVessel(
629
+ /** Earlier vessels of a pane holding exactly this reply, newest fetch first (the search findMarkedVessel describes). */
630
+ async function sameReplyVessels(
641
631
  paneId: string,
642
632
  text: string,
643
- opts: { root?: string; storeRoot?: string; exclude?: string } = {},
644
- ): Promise<{ vessel: string; doc: string; source: SourceIdentity } | null> {
633
+ opts: { root?: string; exclude?: string } = {},
634
+ ): Promise<{ vessel: string; doc: string; source: SourceIdentity }[]> {
645
635
  const root = opts.root ?? resolveVesselRoot()
646
636
  const webDir = join(root, WEB_VESSEL_SUBDIR)
647
637
  const dirs = async (dir: string) =>
@@ -669,10 +659,46 @@ export async function findMarkedVessel(
669
659
  }
670
660
  // Stable: vessels without fetched_at keep their name order.
671
661
  matches.sort((a, b) => String(b.source.fetched_at ?? "").localeCompare(String(a.source.fetched_at ?? "")))
672
- for (const m of matches) if ((await listMarks(m.doc, opts.storeRoot)).length > 0) return m
662
+ return matches
663
+ }
664
+
665
+ /**
666
+ * The newest earlier vessel that holds this very reply from this very pane and
667
+ * has marks on it. Fetching reopens it instead of keeping a fresh copy, so
668
+ * marks another person made on the reply are there when it is fetched again
669
+ * (Episode 339: William opens an agent in the cockpit and finds Mia's marks).
670
+ * Two layouts are searched: web runs at `<root>/web/<run>/<vessel>/` and
671
+ * terminal `tan` runs at `<root>/<stamp>-<target>/`, which the review script
672
+ * gives a `source.json` since jgwill/gaia#87. Their stamps are not comparable
673
+ * (UTC vs local time), so matches are ordered by `fetched_at`.
674
+ * Null when the reply changed since, or nobody marked it.
675
+ */
676
+ export async function findMarkedVessel(
677
+ paneId: string,
678
+ text: string,
679
+ opts: { root?: string; storeRoot?: string; exclude?: string } = {},
680
+ ): Promise<{ vessel: string; doc: string; source: SourceIdentity } | null> {
681
+ for (const m of await sameReplyVessels(paneId, text, opts)) if ((await listMarks(m.doc, opts.storeRoot)).length > 0) return m
673
682
  return null
674
683
  }
675
684
 
685
+ /**
686
+ * The vessel a fetch of this reply reopens: the newest one already marked,
687
+ * else the newest one holding the same reply. So the cockpit and every
688
+ * terminal that fetch the same reply share one document from the first fetch:
689
+ * their marks meet on it, and so does who is writing there (jgwill/Miadi#643).
690
+ * Null when nobody fetched this reply from this pane before.
691
+ */
692
+ export async function findReplyVessel(
693
+ paneId: string,
694
+ text: string,
695
+ opts: { root?: string; storeRoot?: string; exclude?: string } = {},
696
+ ): Promise<{ vessel: string; doc: string; source: SourceIdentity; marked: boolean } | null> {
697
+ const matches = await sameReplyVessels(paneId, text, opts)
698
+ for (const m of matches) if ((await listMarks(m.doc, opts.storeRoot)).length > 0) return { ...m, marked: true }
699
+ return matches[0] ? { ...matches[0], marked: false } : null
700
+ }
701
+
676
702
  /**
677
703
  * Resolve the agent under `target`, read its last reply, and keep it in a fresh
678
704
  * vessel together with the pane's identity. When an earlier vessel already holds
@@ -700,11 +726,12 @@ export async function fetchReply(target: string, opts: { pick?: number; host?: A
700
726
  const source: SourceIdentity = { target, ...here, ...parseAgentFromLog(log), fetched_at: new Date().toISOString() }
701
727
  await writeFile(join(vessel, SOURCE_FILE), JSON.stringify(source, null, 2) + "\n", "utf8")
702
728
  const text = await readFile(doc, "utf8")
703
- const earlier = await findMarkedVessel(here.pane_id, text, { exclude: webRoot })
729
+ // The same reply fetched before keeps its document: everyone's marks and presence meet on one copy.
730
+ const earlier = await findReplyVessel(here.pane_id, text, { exclude: webRoot })
704
731
  if (earlier) {
705
732
  await rm(webRoot, { recursive: true, force: true })
706
733
  const blocks = await listBlocks(earlier.doc, text)
707
- return { id: earlier.doc, target, vessel: earlier.vessel, doc: earlier.doc, text, blocks, source: earlier.source, log, reopened: true }
734
+ return { id: earlier.doc, target, vessel: earlier.vessel, doc: earlier.doc, text, blocks, source: earlier.source, log, ...(earlier.marked ? { reopened: true } : {}) }
708
735
  }
709
736
  const blocks = await listBlocks(doc, text)
710
737
  return { id: doc, target, vessel, doc, text, blocks, source, log }
package/src/client.ts CHANGED
@@ -544,7 +544,7 @@ export function normalizePaneTarget(pane: string): string {
544
544
 
545
545
  export interface SendKeysOptions extends TideRunOptions {
546
546
  /**
547
- * Append a trailing Enter (`C-m`) after typing the literal text. Default true.
547
+ * Append a trailing Enter after typing the literal text. Default true.
548
548
  * When false the text is left on the pane's prompt unsubmitted, so a human can
549
549
  * review and press Enter — the "send Enter after content" cockpit toggle.
550
550
  */
@@ -612,7 +612,9 @@ export function buildSendKeysPlan(
612
612
  submitted: submit,
613
613
  // `-l` types the bytes literally (no tmux key-name interpretation).
614
614
  literal_command: ["send-keys", "-l", "-t", target, message],
615
- submit_command: submit ? ["send-keys", "-t", target, "C-m"] : null,
615
+ // Enter and Ctrl-M diverge under tmux extended keys (Pi enables this).
616
+ // Send the semantic key, not its legacy control-character alias.
617
+ submit_command: submit ? ["send-keys", "-t", target, "Enter"] : null,
616
618
  }
617
619
  }
618
620
 
@@ -625,8 +627,6 @@ export function buildSendKeysPlan(
625
627
  export const PANE_KEYS = ["Up", "Down", "Enter"] as const
626
628
  export type PaneKey = (typeof PANE_KEYS)[number]
627
629
 
628
- const TMUX_KEY_NAME: Record<PaneKey, string> = { Up: "Up", Down: "Down", Enter: "C-m" }
629
-
630
630
  export function isPaneKey(value: unknown): value is PaneKey {
631
631
  return typeof value === "string" && (PANE_KEYS as readonly string[]).includes(value)
632
632
  }
@@ -634,7 +634,7 @@ export function isPaneKey(value: unknown): value is PaneKey {
634
634
  /** The exact `tmux send-keys` argv for one key, without executing it. */
635
635
  export function buildPaneKeyPlan(pane: string, key: PaneKey): { target: string; key: PaneKey; command: string[] } {
636
636
  const target = normalizePaneTarget(pane)
637
- return { target, key, command: ["send-keys", "-t", target, TMUX_KEY_NAME[key]] }
637
+ return { target, key, command: ["send-keys", "-t", target, key] }
638
638
  }
639
639
 
640
640
  /**
@@ -674,8 +674,7 @@ export async function sendPaneKey(
674
674
  * Robust and simple: no shell, no Python spawn, no reviewed-proposal artifact.
675
675
  * Set `submit: false` to type the content without pressing Enter.
676
676
  *
677
- * Two tmux invocations when submitting: the literal text is typed first, then a
678
- * separate `C-m` submits it. If the literal step succeeds but the submit step
677
+ * The literal text is typed first, then a separate `Enter` submits it. If the literal step succeeds but the submit step
679
678
  * fails, the text is already on the pane's prompt (unsubmitted) — the thrown
680
679
  * `TideError` names which step failed so the caller can surface that partial state.
681
680
  *
@@ -977,3 +976,206 @@ export async function setSessionTeam(session: string, team: string | null, opts:
977
976
  throw new TideError(`tmux set-option @miadi-team on session ${name} failed: ${msg}`, err)
978
977
  }
979
978
  }
979
+
980
+ // ── Drafts being prepared (jgwill/Miadi#691, Episode 548 S2 and H3) ─────────
981
+ //
982
+ // `tide drafts list --json` prints one object per open draft, without its words.
983
+ // These verbs never pass `--text`, and `listDrafts` drops a `text` key if a runtime
984
+ // ever printed one anyway: the words of a draft stay with its author's pane.
985
+
986
+ /** Where the labels of a mctgo draft point, by kind. A shell draft has none. */
987
+ export interface TideDraftLabels {
988
+ paths?: string[]
989
+ packages?: string[]
990
+ repositories?: string[]
991
+ addresses?: string[]
992
+ issues?: string[]
993
+ team?: string
994
+ }
995
+
996
+ /** One draft as `tide drafts list --json` gives it (ironsilk ≥ 0.9.60), never its words. */
997
+ export interface TideDraft {
998
+ id: string
999
+ subject: string
1000
+ state: string
1001
+ /** `mctgo` (a session being prepared on a team) or `shell` (an unsent line at a shell prompt). */
1002
+ kind: string
1003
+ pane: string
1004
+ team: string | null
1005
+ target_session: string | null
1006
+ session_id: string | null
1007
+ labels: TideDraftLabels
1008
+ version: number
1009
+ chars: number
1010
+ in_view: boolean
1011
+ reason: string | null
1012
+ /** A ready draft's moment, ISO UTC (ironsilk ≥ 0.9.61). Null when judged or not ready. */
1013
+ send_at?: string | null
1014
+ /** `judged` when a scheduler seat chooses the moment. */
1015
+ scheduler?: string | null
1016
+ /** How late after its moment a ready draft may still go. Null unless ready. */
1017
+ window_seconds?: number | null
1018
+ opened_at: string | null
1019
+ changed_at: string | null
1020
+ closed_at: string | null
1021
+ }
1022
+
1023
+ /** What `withdrawDraft` names: a full id, `draft:<id>`, or a prefix of 4 or more. */
1024
+ export const DRAFT_REF_PATTERN = /^(?:draft:)?[0-9a-f]{4,64}$/
1025
+
1026
+ /** The longest reason passed to the runtime; it is written in the event as given. */
1027
+ export const DRAFT_REASON_MAX = 500
1028
+
1029
+ /**
1030
+ * The drafts tide holds: open ones, and with `all` the closed ones of the last 7 days.
1031
+ * One `tide drafts list --json` call. Lines that are not JSON objects are skipped.
1032
+ */
1033
+ export async function listDrafts(opts: TideRunOptions & { all?: boolean } = {}): Promise<TideDraft[]> {
1034
+ const bin = await resolveTideBin()
1035
+ const args = ["drafts", "list", "--json", ...(opts.all ? ["--all"] : [])]
1036
+ const timeoutMs = opts.timeoutMs ?? 15_000
1037
+ const startedAt = Date.now()
1038
+ let stdout: string
1039
+ try {
1040
+ ;({ stdout } = await pExecFile(bin, args, { timeout: timeoutMs, cwd: opts.cwd, maxBuffer: 8 * 1024 * 1024 }))
1041
+ } catch (err) {
1042
+ throw classifyExecFailure(bin, args, err, Date.now() - startedAt, timeoutMs)
1043
+ }
1044
+ const drafts: TideDraft[] = []
1045
+ for (const line of stdout.split("\n")) {
1046
+ if (!line.trim()) continue
1047
+ let row: unknown
1048
+ try {
1049
+ row = JSON.parse(line)
1050
+ } catch {
1051
+ continue
1052
+ }
1053
+ if (!row || typeof row !== "object" || Array.isArray(row)) continue
1054
+ const { text: _words, ...draft } = row as Record<string, unknown>
1055
+ if (typeof draft.id !== "string") continue
1056
+ drafts.push(draft as unknown as TideDraft)
1057
+ }
1058
+ return drafts
1059
+ }
1060
+
1061
+ export interface TideDraftWithdrawal {
1062
+ /** The id the runtime closed, from its answer line. */
1063
+ id: string
1064
+ /** The runtime's one line: `tide.draft.withdrawn <id> <pane> <reason>`. */
1065
+ line: string
1066
+ }
1067
+
1068
+ /**
1069
+ * Close a draft as withdrawn (`tide.draft.withdrawn`). A restore never types it back.
1070
+ * A refusal (no such draft, a prefix naming several, a closed draft, one being typed
1071
+ * back) is a `TideError` of kind `exit` whose `detail.stderr` carries the runtime's reason.
1072
+ */
1073
+ /** `--by`: the person whose decision this is, named as the event's actor (ironsilk 0.9.62). */
1074
+ const byArgs = (by: string | undefined): string[] => {
1075
+ if (by === undefined) return []
1076
+ if (!DRAFT_BY_PATTERN.test(by)) throw new TideError(`"${by}" is not a person id`)
1077
+ return ["--by", by]
1078
+ }
1079
+
1080
+ /** What tide accepts as `--by`. */
1081
+ export const DRAFT_BY_PATTERN = /^[\w.:@+-]{1,200}$/
1082
+
1083
+ export async function withdrawDraft(ref: string, opts: TideRunOptions & { reason?: string; by?: string } = {}): Promise<TideDraftWithdrawal> {
1084
+ const id = draftRef(ref)
1085
+ const reason = (opts.reason ?? "").replace(/[\s\u0000-\u001f\u007f]+/g, " ").trim()
1086
+ if (reason.length > DRAFT_REASON_MAX) throw new TideError(`a reason is at most ${DRAFT_REASON_MAX} characters`)
1087
+ const line = await runDraftVerb(["drafts", "withdraw", id, ...(reason ? ["--reason", reason] : []), ...byArgs(opts.by)], opts)
1088
+ const closed = /^tide\.draft\.withdrawn\s+([0-9a-f]+)/.exec(line)?.[1]
1089
+ return { id: closed ?? id.replace(/^draft:/, ""), line }
1090
+ }
1091
+
1092
+ /** What `readyDraft` asks for: one of a time, a delay, or a scheduler's judgment. */
1093
+ export type DraftReadyWhen =
1094
+ | { at: string }
1095
+ | { in: string }
1096
+ | { judged: true }
1097
+
1098
+ /** `14:30`, or an ISO time (`2026-10-31T14:30`, with or without an offset): what `--at` reads. */
1099
+ export const DRAFT_AT_PATTERN = /^(?:\d{1,2}:\d{2}|\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:\d{2})?)$/
1100
+ /** `90s`, `45m`, `1h`, `4h30m`, `2d`: what `--in` and `--window` read. */
1101
+ export const DRAFT_DURATION_PATTERN = /^(?:\d{1,4}(?:\.\d{1,3})?[smhd]){1,4}$/
1102
+
1103
+ export interface TideDraftReadied {
1104
+ id: string
1105
+ /** The moment tide will send at, ISO UTC; null when a scheduler judges it. */
1106
+ send_at: string | null
1107
+ judged: boolean
1108
+ window_seconds: number | null
1109
+ line: string
1110
+ }
1111
+
1112
+ /** Run one `tide drafts <verb>` that answers a single line, or throw the classified failure. */
1113
+ async function runDraftVerb(args: string[], opts: TideRunOptions): Promise<string> {
1114
+ const bin = await resolveTideBin()
1115
+ const timeoutMs = opts.timeoutMs ?? 15_000
1116
+ const startedAt = Date.now()
1117
+ try {
1118
+ const { stdout } = await pExecFile(bin, args, { timeout: timeoutMs, cwd: opts.cwd })
1119
+ return stdout.trim().split("\n").pop() ?? ""
1120
+ } catch (err) {
1121
+ throw classifyExecFailure(bin, args, err, Date.now() - startedAt, timeoutMs)
1122
+ }
1123
+ }
1124
+
1125
+ function draftRef(ref: string): string {
1126
+ const id = ref.trim()
1127
+ if (!DRAFT_REF_PATTERN.test(id)) {
1128
+ throw new TideError(`"${ref}" is not a draft id: hex, 4 to 64 characters, optionally after "draft:"`)
1129
+ }
1130
+ return id
1131
+ }
1132
+
1133
+ /**
1134
+ * Flag a mctgo draft's present text ready to be sent at a moment (`tide.draft.readied`,
1135
+ * Episode 548 R1). The flag is the person's consent for that one text; tide presses Enter
1136
+ * at the moment only when nobody has the pane in front of them (R2). Changing the text,
1137
+ * `unreadyDraft`, or a missed window ends it. Refusals are `TideError`s of kind `exit`.
1138
+ */
1139
+ export async function readyDraft(
1140
+ ref: string,
1141
+ when: DraftReadyWhen,
1142
+ opts: TideRunOptions & { window?: string; by?: string } = {},
1143
+ ): Promise<TideDraftReadied> {
1144
+ const id = draftRef(ref)
1145
+ const args = ["drafts", "ready", id]
1146
+ if ("at" in when) {
1147
+ if (!DRAFT_AT_PATTERN.test(when.at)) throw new TideError(`"${when.at}" is not a time: 14:30, or an ISO time`)
1148
+ args.push("--at", when.at)
1149
+ } else if ("in" in when) {
1150
+ if (!DRAFT_DURATION_PATTERN.test(when.in)) throw new TideError(`"${when.in}" is not a duration: 90m, 1h, 4h30m, 2d`)
1151
+ args.push("--in", when.in)
1152
+ } else if (when.judged === true) {
1153
+ args.push("--judged")
1154
+ } else {
1155
+ throw new TideError("say when: at a time, in a delay, or judged")
1156
+ }
1157
+ if (opts.window !== undefined) {
1158
+ if (!DRAFT_DURATION_PATTERN.test(opts.window)) throw new TideError(`"${opts.window}" is not a window: 30m, 1h, 2h`)
1159
+ args.push("--window", opts.window)
1160
+ }
1161
+ args.push(...byArgs(opts.by))
1162
+ const line = await runDraftVerb(args, opts)
1163
+ // tide.draft.readied <id> <pane> <send_at | judged> window <n> s
1164
+ const m = /^tide\.draft\.readied\s+([0-9a-f]+)\s+\S+\s+(\S+)\s+window\s+(\d+)\s*s/.exec(line)
1165
+ const moment = m?.[2] ?? null
1166
+ return {
1167
+ id: m?.[1] ?? id.replace(/^draft:/, ""),
1168
+ send_at: moment && moment !== "judged" ? moment : null,
1169
+ judged: moment === "judged" || "judged" in when,
1170
+ window_seconds: m ? Number(m[3]) : null,
1171
+ line,
1172
+ }
1173
+ }
1174
+
1175
+ /** End a draft's ready flag (`tide.draft.unreadied`). It stays at its prompt, unsent. */
1176
+ export async function unreadyDraft(ref: string, opts: TideRunOptions & { by?: string } = {}): Promise<{ id: string; line: string }> {
1177
+ const id = draftRef(ref)
1178
+ const line = await runDraftVerb(["drafts", "unready", id, ...byArgs(opts.by)], opts)
1179
+ const closed = /^tide\.draft\.unreadied\s+([0-9a-f]+)/.exec(line)?.[1]
1180
+ return { id: closed ?? id.replace(/^draft:/, ""), line }
1181
+ }