@miadi/connector 0.1.35 → 0.1.36

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/dist/approve.js CHANGED
@@ -224,6 +224,8 @@ export function transcriptJobIo(deps) {
224
224
  ...(deps.captions ? { captions: deps.captions } : {}),
225
225
  ...(deps.localTranscription ? { local: deps.localTranscription } : {}),
226
226
  log: (event) => logDecision(deps, event),
227
+ // Shared with the worker script, so no two processes run one review's job at once.
228
+ lockDir: join(deps.config.stateDir, "transcript-locks"),
227
229
  // A job's ending is a fact of its own, recorded in the event ledger on the review's trace (jgwill/Miadi#995).
228
230
  ...(deps.eventsDir ? { outcome: (job, receipt) => announceTranscriptOutcome(job, receipt, deps.eventsDir) } : {}),
229
231
  };
package/dist/tools.js CHANGED
@@ -532,9 +532,10 @@ export function registerTools(server, ctx) {
532
532
  const r = await reviews.get(id);
533
533
  if (!r)
534
534
  throw new ToolRefusal("not_found", "No review with this id.");
535
- if (typeof r.video_id !== "string")
535
+ const video = typeof r.video_id === "string" && r.video_id ? r.video_id : typeof r.video_url === "string" ? videoIdOf(r.video_url) : null;
536
+ if (!video)
536
537
  throw new ToolRefusal("invalid_ref", "This review names no YouTube video, so it has no transcript to acquire.");
537
- return { review_id: id, video_id: r.video_id };
538
+ return { review_id: id, video_id: video };
538
539
  }
539
540
  const video = videoIdOf(input);
540
541
  if (!video)
@@ -17,6 +17,7 @@
17
17
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
18
18
  import { join } from "node:path";
19
19
  import { reviewCreatedOf } from "@miadi/hooks-core";
20
+ import { videoIdOf } from "./reviews.js";
20
21
  import { ensureTranscript } from "./transcript-job.js";
21
22
  /** How many facts one pass starts: each fetches captions from YouTube, so a burst is spread over passes. */
22
23
  export const INTAKE_PER_PASS = 3;
@@ -91,8 +92,10 @@ export async function settleTranscriptRequests(io, o) {
91
92
  result.kept += 1;
92
93
  continue;
93
94
  }
94
- if (review?.video_id !== fact.review.video_id) {
95
- reject(`The review's video is ${String(review?.video_id)}, not ${fact.review.video_id}.`);
95
+ // A review row may carry its video only as an address (video_id null), as the event's builder reads it too.
96
+ const reviewVideo = typeof review?.video_id === "string" && review.video_id ? review.video_id : typeof review?.video_url === "string" ? videoIdOf(review.video_url) : null;
97
+ if (reviewVideo !== fact.review.video_id) {
98
+ reject(`The review's video is ${String(reviewVideo)}, not ${fact.review.video_id}.`);
96
99
  continue;
97
100
  }
98
101
  const ensured = ensureTranscript(io, {
@@ -99,6 +99,13 @@ export interface TranscriptJobIo {
99
99
  local?: FetchCaptions;
100
100
  now?: () => number;
101
101
  log?: (event: Record<string, unknown>) => void;
102
+ /**
103
+ * A folder every process that runs transcript jobs on this host shares (the connector service, the worker
104
+ * script). An attempt holds `<lockDir>/<review id>` with its process id for as long as it runs, so two
105
+ * processes never run one review's job at once, however long an attempt takes. A lock whose process is
106
+ * gone is taken over. Without it, only this process's own attempts are known.
107
+ */
108
+ lockDir?: string;
102
109
  /** Told once each time a job reaches an ending (stored, held, failed), to announce it as a fact. Never fails the job. */
103
110
  outcome?: (job: ConnectorRecord, receipt: TranscriptJobReceipt) => void | Promise<unknown>;
104
111
  }
@@ -19,6 +19,8 @@
19
19
  * either holds the write tier or registered the source. No separate transcript decision exists.
20
20
  */
21
21
  import { createHash } from "node:crypto";
22
+ import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
23
+ import { join } from "node:path";
22
24
  import { TRANSCRIPT_RETRY_MS, TRANSCRIPT_WINDOW_MS, coverage, sourceOf } from "./captions.js";
23
25
  import { current, newRecordId } from "./records.js";
24
26
  /** The review service's own transcript door, as the connector's token reaches it. */
@@ -96,6 +98,61 @@ const runningOf = (io) => {
96
98
  running.set(io.ledger, (m = new Map()));
97
99
  return m;
98
100
  };
101
+ /**
102
+ * Takes the review's lock for this process, or answers null when a live process holds it. The release removes
103
+ * the lock only if it is still this process's.
104
+ */
105
+ function takeLock(io, reviewId) {
106
+ if (!io.lockDir)
107
+ return () => { };
108
+ mkdirSync(io.lockDir, { recursive: true, mode: 0o700 });
109
+ const file = join(io.lockDir, reviewId);
110
+ const mine = `${process.pid}\n`;
111
+ for (let tries = 0; tries < 2; tries += 1) {
112
+ try {
113
+ writeFileSync(file, mine, { flag: "wx", mode: 0o600 });
114
+ return () => {
115
+ try {
116
+ if (readFileSync(file, "utf8") === mine)
117
+ unlinkSync(file);
118
+ }
119
+ catch {
120
+ /* already gone */
121
+ }
122
+ };
123
+ }
124
+ catch (error) {
125
+ if (error.code !== "EEXIST")
126
+ throw error;
127
+ }
128
+ let holder = NaN;
129
+ try {
130
+ holder = Number(readFileSync(file, "utf8").trim());
131
+ }
132
+ catch {
133
+ continue; // released between the two calls: try again
134
+ }
135
+ if (Number.isSafeInteger(holder) && holder > 0 && processAlive(holder))
136
+ return null;
137
+ // Its process is gone (a stop or a crash): the lock is taken over.
138
+ try {
139
+ unlinkSync(file);
140
+ }
141
+ catch {
142
+ /* another taker removed it first */
143
+ }
144
+ }
145
+ return null;
146
+ }
147
+ function processAlive(pid) {
148
+ try {
149
+ process.kill(pid, 0);
150
+ return true;
151
+ }
152
+ catch (error) {
153
+ return error.code === "EPERM";
154
+ }
155
+ }
99
156
  function commit(io, job, receipt, note) {
100
157
  const before = receiptOf(job)?.state;
101
158
  const next = io.ledger.appendDurable({
@@ -387,6 +444,10 @@ export function ensureTranscript(io, input) {
387
444
  }
388
445
  }
389
446
  const start = job;
447
+ // Another process on this host runs this review's attempt now: this trigger joins it by waiting for nothing.
448
+ const release = takeLock(io, input.review_id);
449
+ if (!release)
450
+ return { job: start, joined: true, done: Promise.resolve(current(io.ledger.all()).find((r) => r.id === start.id) ?? start) };
390
451
  const run = (async () => {
391
452
  // A stored job is confirmed against the service and written again only if the service no longer holds the words.
392
453
  if (prior?.state === "stored") {
@@ -403,6 +464,7 @@ export function ensureTranscript(io, input) {
403
464
  return current(io.ledger.all()).find((r) => r.id === start.id) ?? start;
404
465
  });
405
466
  const tracked = run.finally(() => {
467
+ release();
406
468
  if (jobs.get(input.review_id) === tracked)
407
469
  jobs.delete(input.review_id);
408
470
  });
@@ -425,16 +487,21 @@ export async function settleTranscriptJobs(io, o = {}) {
425
487
  // An attempt that is not waiting for a retry and that this process does not run is one a restart interrupted, or one
426
488
  // a worker's own process runs. At start (resumeAll) the first is certain. Later, it is resumed only once its last
427
489
  // stage is older than STALE_MS, so a worker's attempt in its own process is left alone.
490
+ // With a lock folder, the lock says whether another process runs the attempt, so a free lock is resumed at once.
428
491
  const heartbeat = Date.parse(r.stages.at(-1)?.at ?? r.last_attempt_at ?? r.since);
429
- const interrupted = !r.next_attempt_at && (o.resumeAll === true || clock(io) - heartbeat >= STALE_MS);
492
+ const interrupted = !r.next_attempt_at && (o.resumeAll === true || Boolean(io.lockDir) || clock(io) - heartbeat >= STALE_MS);
430
493
  const due = (r.state === "acquiring" && (r.next_attempt_at ? Date.parse(r.next_attempt_at) <= clock(io) : interrupted)) ||
431
494
  (r.state === "held" && sourceStatus(io.ledger.all(), r.video_id) !== "withheld");
432
495
  if (!due)
433
496
  continue;
497
+ const release = takeLock(io, r.review_id);
498
+ if (!release)
499
+ continue; // another process on this host is running it
434
500
  const resumed = r.state === "held" ? { ...r, since: iso(clock(io)) } : r;
435
501
  const base = resumed === r ? job : commit(io, job, resumed);
436
502
  const run = attempt(io, base).catch(() => base);
437
503
  const tracked = run.finally(() => {
504
+ release();
438
505
  if (jobs.get(r.review_id) === tracked)
439
506
  jobs.delete(r.review_id);
440
507
  });
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.35";
1
+ export declare const VERSION = "0.1.36";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.1.35";
1
+ export const VERSION = "0.1.36";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/connector",
3
- "version": "0.1.35",
3
+ "version": "0.1.36",
4
4
  "description": "The Miadi connector: one remote MCP service through which a person signed in with their Miadi person token, from ChatGPT or any MCP client, reads sessions, reviews, episodes and circles and records observations, inquiries, handoffs and proposals with their name on each record.",
5
5
  "license": "MIT",
6
6
  "author": "Miadi",
@@ -44,7 +44,7 @@
44
44
  ],
45
45
  "dependencies": {
46
46
  "@miadi/hooks-core": "^0.6.0",
47
- "@miadi/hooks-gateway": "^0.2.0",
47
+ "@miadi/hooks-gateway": "^0.2.1",
48
48
  "@miadi/inquiry-weave": "0.18.13",
49
49
  "@miadi/node-service-kit": "0.1.2",
50
50
  "@modelcontextprotocol/sdk": "^1.30.0",