@synap-core/workspace-templates 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -279,6 +279,7 @@ proposal; the review is the catalog commit.
279
279
  | `activators[]` (workers) | playbook | `on`: `created` · `enters_status` (+ `status`) · `count` (+ `status`, `min` ≥ 2) · `schedule` (+ `cron`, UTC) · `manual`. `size`: `per_thing` (default) · `per_moment` (count and schedule always are). `mode`: `propose` (default) · `run` only when cheap and safe. `maxPendingApprovals` (default 20) throttles. Compiled to a governed rule the owner can pause; it fires once per thing per transition. |
280
280
  | `goalTemplate` | playbook | Placeholders are `{paramName}`. Never `@{arg:…}` (read-only legacy). |
281
281
  | `params` | playbook | The subject is a `type: entity` param. A required param left unanswered becomes a question owed by the person, not an empty string. |
282
+ | `guidance[]` | playbook | The rules it follows (backend#924): `{ref: "kind:<slug>" \| "skill:<slug>", label?, when?, where?}`, refs never ids. Each run renders the CURRENT versions under "Rules this playbook follows": a kind's entities whose lifecycle category is `done`, an approved skill. So a `kind:` ref names a catalog kind with a lifecycle whose done options are all `humanOnly` (entity text becomes prompt text); a kind with an `order` property renders as "the first row that fits". Style lives here, never in the goal; process stays in the goal. `guidance-ref` in `synap catalog validate`. |
282
283
 
283
284
  Human moments use an `ask` on an owed slot: `confirm` / `choose` (one `recommended`) / `form` / `act` / `provide`
284
285
  (connection, file or secret through the vault). Never ask for a secret in a form.
@@ -367,7 +368,7 @@ computer fills: `{home}`, `{brewPrefix}`, `{tools}`, `{models}`, `{workdir}`, `{
367
368
  (decision 5): validate flags each one (`computer-untested-os`, a warning).
368
369
 
369
370
  **Recipes are stored config.** `media-ffmpeg` does every effect through one verb with a recipe library in
370
- `spec.recipes` (reframe, loudness, silence cut, word captions, grade, crossfade, overlay, background replace,
371
+ `spec.recipes` (range cut, reframe, loudness, silence cut, word captions, grade, crossfade, overlay, background replace,
371
372
  slideshow, GIF/WebP, keyframes, platform exports). A recipe is:
372
373
 
373
374
  ```jsonc
@@ -16,7 +16,7 @@
16
16
  "spec": {
17
17
  "key": "media-download",
18
18
  "name": "Download videos on your computer",
19
- "description": "yt-dlp (public domain, Unlicense) installed with uv as yt-dlp[default], which bundles yt-dlp-ejs for YouTube's JavaScript challenges; the challenges run on Node 22+, which the synap CLI already needs (--js-runtimes node). Needs media-ffmpeg to merge video and audio and extract audio. TERMS: downloading may breach a platform's terms of service and the creator's copyright; use it only for content you own, are licensed to use, or use under fair-use review, never as a re-upload pipeline.",
19
+ "description": "yt-dlp (public domain, Unlicense) installed with uv as yt-dlp[default,deno]: yt-dlp-ejs for YouTube's JavaScript challenges, and deno (MIT), the runtime that solves them, inside the tool's own environment, where yt-dlp finds it with no flag and no PATH change (on Mac, Linux and Windows). Needs media-ffmpeg to merge video and audio and extract audio. TERMS: downloading may breach a platform's terms of service and the creator's copyright; use it only for content you own, are licensed to use, or use under fair-use review, never as a re-upload pipeline.",
20
20
  "licence": "Unlicense",
21
21
  "placement": {
22
22
  "runsOn": [
@@ -54,8 +54,7 @@
54
54
  }
55
55
  ],
56
56
  "runtimes": {
57
- "uv": ">=0.5",
58
- "node": ">=22"
57
+ "uv": ">=0.5"
59
58
  }
60
59
  }
61
60
  },
@@ -65,7 +64,7 @@
65
64
  {
66
65
  "kind": "uv",
67
66
  "action": "tool-install",
68
- "package": "yt-dlp[default]"
67
+ "package": "yt-dlp[default,deno]"
69
68
  }
70
69
  ],
71
70
  "bins": {
@@ -77,7 +76,7 @@
77
76
  {
78
77
  "kind": "uv",
79
78
  "action": "tool-install",
80
- "package": "yt-dlp[default]"
79
+ "package": "yt-dlp[default,deno]"
81
80
  }
82
81
  ],
83
82
  "bins": {
@@ -89,7 +88,7 @@
89
88
  {
90
89
  "kind": "uv",
91
90
  "action": "tool-install",
92
- "package": "yt-dlp[default]"
91
+ "package": "yt-dlp[default,deno]"
93
92
  }
94
93
  ],
95
94
  "bins": {
@@ -97,7 +96,7 @@
97
96
  }
98
97
  },
99
98
  "elevation": "never",
100
- "diskFreeMb": 200
99
+ "diskFreeMb": 350
101
100
  },
102
101
  "verify": {
103
102
  "darwin": {
@@ -113,8 +112,7 @@
113
112
  "smoke": {
114
113
  "command": [
115
114
  "yt-dlp",
116
- "--js-runtimes",
117
- "node",
115
+ "-v",
118
116
  "--simulate",
119
117
  "--print",
120
118
  "id",
@@ -122,7 +120,8 @@
122
120
  ],
123
121
  "expect": {
124
122
  "exitCode": 0,
125
- "stdoutContains": "jNQXAC9IVRw"
123
+ "stdoutContains": "jNQXAC9IVRw",
124
+ "stderrMatches": "^\\[debug\\] JS runtimes: deno-"
126
125
  }
127
126
  }
128
127
  },
@@ -139,8 +138,7 @@
139
138
  "smoke": {
140
139
  "command": [
141
140
  "yt-dlp",
142
- "--js-runtimes",
143
- "node",
141
+ "-v",
144
142
  "--simulate",
145
143
  "--print",
146
144
  "id",
@@ -148,7 +146,8 @@
148
146
  ],
149
147
  "expect": {
150
148
  "exitCode": 0,
151
- "stdoutContains": "jNQXAC9IVRw"
149
+ "stdoutContains": "jNQXAC9IVRw",
150
+ "stderrMatches": "^\\[debug\\] JS runtimes: deno-"
152
151
  }
153
152
  }
154
153
  },
@@ -165,8 +164,7 @@
165
164
  "smoke": {
166
165
  "command": [
167
166
  "yt-dlp",
168
- "--js-runtimes",
169
- "node",
167
+ "-v",
170
168
  "--simulate",
171
169
  "--print",
172
170
  "id",
@@ -174,7 +172,8 @@
174
172
  ],
175
173
  "expect": {
176
174
  "exitCode": 0,
177
- "stdoutContains": "jNQXAC9IVRw"
175
+ "stdoutContains": "jNQXAC9IVRw",
176
+ "stderrMatches": "^\\[debug\\] JS runtimes: deno-"
178
177
  }
179
178
  }
180
179
  },
@@ -229,7 +228,7 @@
229
228
  "kind": "instruction",
230
229
  "scope": "pod",
231
230
  "description": "How to download a video or its audio with yt-dlp on the computer that has it, and the terms rule that comes first.",
232
- "code": "# Download a video or its audio on this computer\n\n**First, the rule.** Downloading can breach a platform's terms of service and the creator's copyright. Download only what the person owns, is licensed to use, or uses under a fair-use review they have done. Never use it to re-upload someone else's video. When it is not clear, ask.\n\n1. Check the tool is here: `synap tools verify media-download`. Not installed: ask the person first.\n2. YouTube needs a JavaScript runtime to solve its challenges: always pass `--js-runtimes node` (Node 22 or later is on every computer that runs the synap CLI).\n3. Ask yt-dlp to print where the file landed: `--print after_move:filepath`.\n\n```\n# the best MP4 (H.264 + AAC), the easiest file to edit\nyt-dlp --js-runtimes node -t mp4 -P OUT_DIR -o \"%(upload_date>%Y-%m-%d)s %(title).80B [%(id)s].%(ext)s\" --print after_move:filepath URL\n# audio only, ready to transcribe (16 kHz mono WAV)\nyt-dlp --js-runtimes node -x --audio-format wav --postprocessor-args \"ExtractAudio:-ar 16000 -ac 1\" -P OUT_DIR URL\n# one section, with subtitles, metadata and the thumbnail\nyt-dlp --js-runtimes node -t mp4 --download-sections \"*00:01:10-00:02:05\" --write-subs --write-auto-subs --sub-langs \"en.*,fr.*\" --write-info-json --write-thumbnail -P OUT_DIR URL\n```\n\nStore the source URL with the file, so where it came from is never lost.\n\n**Gotchas**\n- yt-dlp merges video and audio with ffmpeg: media-ffmpeg must be installed on the same computer; pass `--ffmpeg-location` with its pinned path.\n- Logged-in content (`--cookies-from-browser firefox`) reads the person's browser cookies: only with their explicit yes, and with a dedicated account (a logged-in account can be rate-limited or banned). Chrome cookies often fail on Windows; prefer Firefox.\n- `.80B` in the name template cuts the title at 80 bytes, safe on every filesystem.\n"
231
+ "code": "# Download a video or its audio on this computer\n\n**First, the rule.** Downloading can breach a platform's terms of service and the creator's copyright. Download only what the person owns, is licensed to use, or uses under a fair-use review they have done. Never use it to re-upload someone else's video. When it is not clear, ask.\n\n1. Check the tool is here: `synap tools verify media-download`. Not installed: ask the person first.\n2. YouTube needs a JavaScript runtime to solve its challenges: the install put deno inside yt-dlp's own environment and yt-dlp uses it by itself, no flag needed. If yt-dlp still warns \"No supported JavaScript runtime could be found\", the tool was installed before deno was part of it: install it again (`synap tools install media-download`).\n3. Ask yt-dlp to print where the file landed: `--print after_move:filepath`.\n\n```\n# the best MP4 (H.264 + AAC), the easiest file to edit\nyt-dlp -t mp4 -P OUT_DIR -o \"%(upload_date>%Y-%m-%d)s %(title).80B [%(id)s].%(ext)s\" --print after_move:filepath URL\n# audio only, ready to transcribe (16 kHz mono WAV)\nyt-dlp -x --audio-format wav --postprocessor-args \"ExtractAudio:-ar 16000 -ac 1\" -P OUT_DIR URL\n# one section, with subtitles, metadata and the thumbnail\nyt-dlp -t mp4 --download-sections \"*00:01:10-00:02:05\" --write-subs --write-auto-subs --sub-langs \"en.*,fr.*\" --write-info-json --write-thumbnail -P OUT_DIR URL\n```\n\nStore the source URL with the file, so where it came from is never lost.\n\n**Gotchas**\n- yt-dlp merges video and audio with ffmpeg: media-ffmpeg must be installed on the same computer; pass `--ffmpeg-location` with its pinned path.\n- Logged-in content (`--cookies-from-browser firefox`) reads the person's browser cookies: only with their explicit yes, and with a dedicated account (a logged-in account can be rate-limited or banned). Chrome cookies often fail on Windows; prefer Firefox.\n- `.80B` in the name template cuts the title at 80 bytes, safe on every filesystem.\n"
233
232
  }
234
233
  ],
235
234
  "provides": []
@@ -4,7 +4,7 @@
4
4
  "meta": {
5
5
  "slug": "media-ffmpeg",
6
6
  "name": "ffmpeg on your computer",
7
- "description": "Edits video and audio on your own computer with ffmpeg and a library of named recipes: vertical crops, captions, loudness, silence cuts, colour, transitions, overlays, background replacement, slideshows, GIFs and platform exports. Nothing leaves the computer. ffmpeg is GPL software, installed from its usual source, never bundled.",
7
+ "description": "Edits video and audio on your own computer with ffmpeg and a library of named recipes: frame-accurate range cuts, vertical crops, captions, loudness, silence cuts, colour, transitions, overlays, background replacement, slideshows, GIFs and platform exports. Nothing leaves the computer. ffmpeg is GPL software, installed from its usual source, never bundled.",
8
8
  "tags": [
9
9
  "capability",
10
10
  "media",
@@ -1177,6 +1177,73 @@
1177
1177
  "Do not normalise loudness here: whisper does not need it."
1178
1178
  ]
1179
1179
  },
1180
+ {
1181
+ "name": "range-cut",
1182
+ "description": "Keep one time range of a video (keep 00:12 to 00:41). Frame-accurate by default: the range is re-encoded at high quality, so it starts on the exact frame asked for, not on the keyframe before it.",
1183
+ "params": {
1184
+ "in": {
1185
+ "type": "file",
1186
+ "description": "The video to work on.",
1187
+ "required": true
1188
+ },
1189
+ "out": {
1190
+ "type": "output",
1191
+ "description": "Where the result is written.",
1192
+ "required": true
1193
+ },
1194
+ "start": {
1195
+ "type": "time",
1196
+ "description": "Where the kept range starts, on the source's clock: seconds (12 or 12.5) or [hh:]mm:ss[.ms] (00:12, 00:00:12.500).",
1197
+ "required": true
1198
+ },
1199
+ "end": {
1200
+ "type": "time",
1201
+ "description": "Where the kept range ends, on the source's clock (a time, not a duration): 00:41 keeps 29 seconds when start is 00:12.",
1202
+ "required": true
1203
+ }
1204
+ },
1205
+ "steps": [
1206
+ {
1207
+ "program": "ffmpeg",
1208
+ "args": [
1209
+ "-y",
1210
+ "-ss",
1211
+ "{start}",
1212
+ "-to",
1213
+ "{end}",
1214
+ "-i",
1215
+ "{in}",
1216
+ "-map",
1217
+ "0:v:0",
1218
+ "-map",
1219
+ "0:a?",
1220
+ "-c:v",
1221
+ "libx264",
1222
+ "-crf",
1223
+ "12",
1224
+ "-preset",
1225
+ "veryfast",
1226
+ "-c:a",
1227
+ "aac",
1228
+ "-b:a",
1229
+ "192k",
1230
+ "{out}"
1231
+ ]
1232
+ }
1233
+ ],
1234
+ "needs": {
1235
+ "encoders": [
1236
+ "libx264",
1237
+ "aac"
1238
+ ]
1239
+ },
1240
+ "gotchas": [
1241
+ "Exact or fast: this recipe re-encodes the range (H.264 at CRF 12, near lossless), which costs encoding time. A stream copy (-c copy) is instant and adds no loss, but it can only start on a keyframe: the file holds everything from the keyframe before start (up to 8 s earlier on a phone or camera file), hidden behind an MP4 edit list that ffmpeg players honour and many editors and web players ignore, and its length is off by a few frames. Use a stream copy only for a rough trim where the first frame does not matter.",
1242
+ "-ss and -to sit before -i: ffmpeg seeks fast to the keyframe before start, then decodes and drops frames up to start, so the cut stays frame-accurate on a long file. Both times are on the source's clock.",
1243
+ "end is a time, not a duration: keep 00:12 to 00:41 is start 00:12, end 00:41 (29 s), never end 29.",
1244
+ "Encode for a platform once, at the end, with an export-* recipe: this output is an intermediate."
1245
+ ]
1246
+ },
1180
1247
  {
1181
1248
  "name": "export-reels",
1182
1249
  "description": "Final export for Instagram Reels, TikTok and YouTube Shorts (1080x1920, 30 fps).",
@@ -273,8 +273,8 @@
273
273
  "name": "transcribe-on-computer",
274
274
  "kind": "instruction",
275
275
  "scope": "pod",
276
- "description": "How to transcribe a video or audio file on the computer that has this tool: extract 16 kHz audio, run mlx-whisper (Mac) or faster-whisper (Linux, Windows) with word timings, keep SRT, VTT and the words JSON.",
277
- "code": "# Transcribe a video or audio file on this computer\n\nThe result is a timed transcript: subtitles (SRT and VTT) and a JSON file with every word's start and end (`segments[].words[]`: word, start, end, probability). The words JSON is what the `captions-burn-in` and silence recipes of media-ffmpeg read. Nothing leaves the computer and no AI tokens are spent.\n\n1. Check the tool is here: `synap tools verify media-transcribe`. Not installed: ask the person before installing (the model is a 1.6 GB download).\n2. Turn the input into 16 kHz mono WAV with the media-ffmpeg recipe `audio-extract` (a video goes in, `audio.wav` comes out).\n3. Run the tool for this computer, with word timings ON and the model named (never the tiny default):\n\n**Mac (Apple Silicon): mlx-whisper**\n```\nmlx_whisper audio.wav --model mlx-community/whisper-large-v3-turbo -f all -o OUT_DIR --word-timestamps True --condition-on-previous-text False\n```\nAdd `--language en` (or fr...) when you know it. For subtitle lines, `--max-words-per-line 4` (it needs word timestamps).\n\n**Linux and Windows: faster-whisper (whisper-ctranslate2)**\n```\nwhisper-ctranslate2 audio.wav --model large-v3-turbo --output_format all --output_dir OUT_DIR --word_timestamps True --vad_filter True\n```\nOn a computer without an NVIDIA GPU add `--device cpu --compute_type int8`.\n\n4. Keep the four files beside the source: `.srt`, `.vtt`, `.txt`, `.json`.\n\n**No Python on the computer?** whisper.cpp is a single program (MIT): `brew install whisper-cpp` on a Mac, or built from github.com/ggml-org/whisper.cpp; then `whisper-cli -m ggml-large-v3-turbo.bin -f audio.wav -osrt -ovtt -ojf -of OUT`. Its full JSON has token timings, not the `segments[].words[]` shape, so the caption recipe cannot read it as is.\n\n**Gotchas**\n- Long silences can make whisper repeat itself: `--condition-on-previous-text False` (mlx) and `--vad_filter True` (faster-whisper) stop it.\n- After a silence cut, transcribe the CUT file again so word timings match.\n- A GPU on Linux needs CUDA 12 and cuDNN 9 for faster-whisper.\n"
276
+ "description": "How to transcribe a video or audio file on the computer that has this tool: extract 16 kHz audio, run mlx-whisper (Mac) or faster-whisper (Linux, Windows) with word timings, keep SRT, VTT and the words JSON, and write transcript.json for the video playbooks.",
277
+ "code": "# Transcribe a video or audio file on this computer\n\nThe result is a timed transcript: subtitles (SRT and VTT) and a JSON file with every word's start and end (`segments[].words[]`: word, start, end, probability). The words JSON is what the `captions-burn-in` and silence recipes of media-ffmpeg read. The video playbooks (Content OS: a take's transcript, \"## Words\") read `transcript.json`, written by step 5 from the words JSON: one `{\"text\", \"start\", \"end\"}` per word, in seconds (HyperFrames' shape). Nothing leaves the computer and no AI tokens are spent.\n\n1. Check the tool is here: `synap tools verify media-transcribe`. Not installed: ask the person before installing (the model is a 1.6 GB download).\n2. Turn the input into 16 kHz mono WAV with the media-ffmpeg recipe `audio-extract` (a video goes in, `audio.wav` comes out).\n3. Run the tool for this computer, with word timings ON and the model named (never the tiny default):\n\n**Mac (Apple Silicon): mlx-whisper**\n```\nmlx_whisper audio.wav --model mlx-community/whisper-large-v3-turbo -f all -o OUT_DIR --word-timestamps True --condition-on-previous-text False\n```\nAdd `--language en` (or fr...) when you know it. For subtitle lines, `--max-words-per-line 4` (it needs word timestamps).\n\n**Linux and Windows: faster-whisper (whisper-ctranslate2)**\n```\nwhisper-ctranslate2 audio.wav --model large-v3-turbo --output_format all --output_dir OUT_DIR --word_timestamps True --vad_filter True\n```\nOn a computer without an NVIDIA GPU add `--device cpu --compute_type int8`.\n\n4. Keep the four files beside the source: `.srt`, `.vtt`, `.txt`, `.json`.\n5. Write `transcript.json`, the file the video playbooks read: save this script as `to_transcript.py` in the scratch folder and run it on the words JSON (`audio.json` when the input was `audio.wav`). Use `python3` (`python` on Windows): Python is already on this computer, jq may not be.\n```\npython3 to_transcript.py OUT_DIR/audio.json OUT_DIR/transcript.json\n```\n```python\n# to_transcript.py WORDS_JSON OUT: whisper's words JSON -> [{\"text\", \"start\", \"end\"}], one entry per word, in seconds\nimport json, sys\nsrc, out = sys.argv[1], sys.argv[2]\nwith open(src, encoding=\"utf-8\") as f:\n data = json.load(f)\nsegments = data.get(\"segments\") if isinstance(data, dict) else None\nif not isinstance(segments, list):\n sys.exit(f\"to_transcript: {src} has no segments: it is not the whisper words JSON (use the .json the transcriber wrote)\")\nif any(not isinstance(s.get(\"words\"), list) for s in segments):\n sys.exit(f\"to_transcript: {src} has no word timings: transcribe again with word timestamps on\")\nwords = [{\"text\": w[\"word\"].strip(), \"start\": round(w[\"start\"], 3), \"end\": round(w[\"end\"], 3)}\n for s in segments for w in s[\"words\"] if w[\"word\"].strip()]\nwith open(out, \"w\", encoding=\"utf-8\") as f:\n json.dump(words, f, ensure_ascii=False, indent=1)\nprint(f\"{out}: {len(words)} words\")\n```\nA JSON with no segments, or with no word timings, stops with a message and exit code 1 and writes nothing: fix the transcription, never hand on an empty file. Audio with no speech gives `[]`, which is a true empty result.\n\n**No Python on the computer?** whisper.cpp is a single program (MIT): `brew install whisper-cpp` on a Mac, or built from github.com/ggml-org/whisper.cpp; then `whisper-cli -m ggml-large-v3-turbo.bin -f audio.wav -osrt -ovtt -ojf -of OUT`. Its full JSON has token timings, not the `segments[].words[]` shape, so the caption recipe cannot read it as is.\n\n**Gotchas**\n- Long silences can make whisper repeat itself: `--condition-on-previous-text False` (mlx) and `--vad_filter True` (faster-whisper) stop it.\n- After a silence cut, transcribe the CUT file again so word timings match.\n- A GPU on Linux needs CUDA 12 and cuDNN 9 for faster-whisper.\n"
278
278
  }
279
279
  ],
280
280
  "provides": []
@@ -306,7 +306,7 @@
306
306
  "intent": "enrich_entity",
307
307
  "kind": "code",
308
308
  "scope": "pod",
309
- "description": "Finds ONE person's LinkedIn profile by their full name and company, on a STRICT match only: the result's name equals the full name (case- and accent-insensitive), the company is in its headline, and exactly one result is both. Pure read -> runs instantly; it writes nothing. A match returns { matched: true, profile, properties: { linkedinUrl, linkedinProviderId } }: propose those properties on the person for a person to approve, never write them directly. No match, several, or more results than it read returns { matched: false, reason: none | several | more_results, candidates } with up to 3 candidates for a person to choose from. Args: { fullName: string, company: string, accountId: string (from unipile_list_accounts) }.",
309
+ "description": "Finds ONE person's LinkedIn profile by their full name and, when known, their company. With a company it matches STRICTLY: the result's name equals the full name (case- and accent-insensitive), the company is in its headline, and exactly one result is both. Pure read -> runs instantly; it writes nothing. A match returns { matched: true, profile, properties: { linkedinUrl, linkedinProviderId } }: propose those properties on the person for a person to approve, never write them directly. No match, several, or more results than it read returns { matched: false, reason: none | several | more_results, candidates } with up to 5 candidates for a person to choose from. Without a company a name alone is never a strict match: it returns up to 5 candidates (reason name_only) for a person to choose. Args: { fullName: string, company?: string, accountId: string (from unipile_list_accounts) }.",
310
310
  "requires": [
311
311
  "unipile_linkedin"
312
312
  ],
@@ -318,7 +318,7 @@
318
318
  },
319
319
  "parameters": {
320
320
  "fullName": "string",
321
- "company": "string",
321
+ "company": "string?",
322
322
  "accountId": "string"
323
323
  },
324
324
  "inputMap": {
@@ -334,7 +334,7 @@
334
334
  "provider": "provider"
335
335
  }
336
336
  },
337
- "code": "// Find ONE person's LinkedIn profile by their full name and company: a STRICT\n// match or none (CRM wave 2, S4b). A pure read: it writes nothing, so it runs at\n// once. Writing the match onto the person (linkedinUrl, linkedinProviderId) is\n// the caller's write, proposed for a person to approve (founder decision 7).\n// STRICT: the result's name equals the full name (case- and accent-insensitive,\n// spaces collapsed), the company is in its headline as whole words (a v2\n// PeopleSearchResult has no company field), and exactly one result is both.\n// None, several, or a third page left unread (so one more could exist): no\n// match, with up to 3 candidates (the closest first) for a person to choose.\n// v2: POST /{account_id}/linkedin/search/people, paged by `cursor` (the reply's\n// next_cursor); the company also narrows the search (advanced_keywords).\nconst accountId = String(args?.accountId ?? '').trim();\nconst fullName = String(args?.fullName ?? '').trim();\nconst company = String(args?.company ?? '').trim();\nif (!accountId) throw new Error('linkedin_find_profile: accountId is required — call unipile_list_accounts first to find yours.');\nif (!fullName) throw new Error('linkedin_find_profile: fullName (the person\\'s first and last name) is required');\nif (!company) throw new Error('linkedin_find_profile: company is required: without it a name alone is never a strict match');\n\nconst fold = (s) => String(s ?? '').normalize('NFD').replace(/\\p{M}+/gu, '').toLowerCase();\nconst nameKey = (s) => fold(s).replace(/\\s+/g, ' ').trim();\nconst words = (s) => fold(s).split(/[^\\p{L}\\p{N}]+/u).filter(Boolean);\nconst hasWords = (text, part) => {\n if (!part.length) return false;\n for (let i = 0; i + part.length <= text.length; i++) {\n if (part.every((w, j) => text[i + j] === w)) return true;\n }\n return false;\n};\nconst wanted = nameKey(fullName);\nconst companyWords = words(company);\nconst nameMatches = (p) => nameKey(p?.display_name) === wanted;\nconst companyInHeadline = (p) => hasWords(words(p?.headline), companyWords);\n\nconst MAX_PAGES = 2;\nconst account = encodeURIComponent(accountId);\nconst body = { keywords: fullName, advanced_keywords: { company } };\nconst byId = new Map();\nlet cursor = null;\nlet pages = 0;\ndo {\n const qs = cursor ? `?${new URLSearchParams({ cursor }).toString()}` : '';\n const res = await callProvider('unipile_linkedin', 'POST', `/${account}/linkedin/search/people${qs}`, body);\n if (res?.proposed === true) {\n return { matched: false, reason: 'proposed', proposed: true, proposalId: res?.proposalId ?? null, candidates: [] };\n }\n if (res?.status && (res.status < 200 || res.status >= 300)) throw new Error(`linkedin_find_profile: the LinkedIn search failed (status ${res.status}).`);\n const payload = res?.body ?? res;\n const items = Array.isArray(payload?.data) ? payload.data : [];\n for (const p of items) {\n const key = String(p?.id ?? p?.public_identifier ?? `row-${byId.size}`);\n if (!byId.has(key)) byId.set(key, p);\n }\n pages += 1;\n const next = typeof payload?.next_cursor === 'string' && payload.next_cursor ? payload.next_cursor : null;\n cursor = next && next !== cursor ? next : null;\n} while (cursor && pages < MAX_PAGES);\nconst moreUnread = Boolean(cursor);\n\nconst view = (p) => {\n const publicIdentifier = p?.public_identifier ?? null;\n return {\n name: String(p?.display_name ?? '').trim() || null,\n headline: p?.headline ?? null,\n location: p?.location ?? null,\n providerId: p?.id ?? null,\n publicIdentifier,\n profileUrl: p?.profile_url ?? (publicIdentifier ? `https://www.linkedin.com/in/${publicIdentifier}` : null),\n networkDistance: p?.network_distance ?? null,\n nameMatches: nameMatches(p),\n companyInHeadline: companyInHeadline(p),\n };\n};\nconst rows = [...byId.values()].map(view);\nconst strict = rows.filter((r) => r.nameMatches && r.companyInHeadline);\nconst searched = { fullName, company, results: rows.length, pages, moreUnread };\n\nif (strict.length === 1 && !moreUnread) {\n const profile = strict[0];\n return {\n matched: true,\n profile,\n properties: { linkedinUrl: profile.profileUrl, linkedinProviderId: profile.providerId },\n candidates: [],\n searched,\n };\n}\nconst rank = (r) => (r.nameMatches ? 2 : 0) + (r.companyInHeadline ? 1 : 0);\nconst candidates = rows\n .map((r, i) => ({ r, i }))\n .sort((a, b) => rank(b.r) - rank(a.r) || a.i - b.i)\n .slice(0, 3)\n .map(({ r }) => r);\nconst reason = strict.length > 1 ? 'several' : strict.length === 1 ? 'more_results' : 'none';\nreturn { matched: false, reason, candidates, searched };\n"
337
+ "code": "// Find ONE person's LinkedIn profile by their full name and, when known, their\n// company: a STRICT match, else candidates to choose from (CRM wave 2, S4b). A pure read: it writes nothing, so it runs at\n// once. Writing the match onto the person (linkedinUrl, linkedinProviderId) is\n// the caller's write, proposed for a person to approve (founder decision 7).\n// STRICT: the result's name equals the full name (case- and accent-insensitive,\n// spaces collapsed), the company is in its headline as whole words (a v2\n// PeopleSearchResult has no company field), and exactly one result is both.\n// None, several, or a third page left unread (so one more could exist): no\n// match, with up to 5 candidates (the closest first) for a person to choose.\n// No company given: a name alone is never a strict match, so it returns the\n// closest candidates (reason name_only) and the person chooses.\n// v2: POST /{account_id}/linkedin/search/people, paged by `cursor` (the reply's\n// next_cursor); the company also narrows the search (advanced_keywords).\nconst accountId = String(args?.accountId ?? '').trim();\nconst fullName = String(args?.fullName ?? '').trim();\nconst company = String(args?.company ?? '').trim();\nif (!accountId) throw new Error('linkedin_find_profile: accountId is required — call unipile_list_accounts first to find yours.');\nif (!fullName) throw new Error('linkedin_find_profile: fullName (the person\\'s first and last name) is required');\n\nconst fold = (s) => String(s ?? '').normalize('NFD').replace(/\\p{M}+/gu, '').toLowerCase();\nconst nameKey = (s) => fold(s).replace(/\\s+/g, ' ').trim();\nconst words = (s) => fold(s).split(/[^\\p{L}\\p{N}]+/u).filter(Boolean);\nconst hasWords = (text, part) => {\n if (!part.length) return false;\n for (let i = 0; i + part.length <= text.length; i++) {\n if (part.every((w, j) => text[i + j] === w)) return true;\n }\n return false;\n};\nconst wanted = nameKey(fullName);\nconst companyWords = words(company);\nconst nameMatches = (p) => nameKey(p?.display_name) === wanted;\nconst companyInHeadline = (p) => hasWords(words(p?.headline), companyWords);\n\nconst MAX_PAGES = 2;\nconst account = encodeURIComponent(accountId);\nconst body = company ? { keywords: fullName, advanced_keywords: { company } } : { keywords: fullName };\nconst byId = new Map();\nlet cursor = null;\nlet pages = 0;\ndo {\n const qs = cursor ? `?${new URLSearchParams({ cursor }).toString()}` : '';\n const res = await callProvider('unipile_linkedin', 'POST', `/${account}/linkedin/search/people${qs}`, body);\n if (res?.proposed === true) {\n return { matched: false, reason: 'proposed', proposed: true, proposalId: res?.proposalId ?? null, candidates: [] };\n }\n if (res?.status && (res.status < 200 || res.status >= 300)) throw new Error(`linkedin_find_profile: the LinkedIn search failed (status ${res.status}).`);\n const payload = res?.body ?? res;\n const items = Array.isArray(payload?.data) ? payload.data : [];\n for (const p of items) {\n const key = String(p?.id ?? p?.public_identifier ?? `row-${byId.size}`);\n if (!byId.has(key)) byId.set(key, p);\n }\n pages += 1;\n const next = typeof payload?.next_cursor === 'string' && payload.next_cursor ? payload.next_cursor : null;\n cursor = next && next !== cursor ? next : null;\n} while (cursor && pages < MAX_PAGES);\nconst moreUnread = Boolean(cursor);\n\nconst view = (p) => {\n const publicIdentifier = p?.public_identifier ?? null;\n return {\n name: String(p?.display_name ?? '').trim() || null,\n headline: p?.headline ?? null,\n location: p?.location ?? null,\n providerId: p?.id ?? null,\n publicIdentifier,\n profileUrl: p?.profile_url ?? (publicIdentifier ? `https://www.linkedin.com/in/${publicIdentifier}` : null),\n networkDistance: p?.network_distance ?? null,\n nameMatches: nameMatches(p),\n companyInHeadline: companyInHeadline(p),\n };\n};\nconst rows = [...byId.values()].map(view);\nconst strict = rows.filter((r) => r.nameMatches && r.companyInHeadline);\nconst searched = { fullName, company: company || null, results: rows.length, pages, moreUnread };\n\nif (company && strict.length === 1 && !moreUnread) {\n const profile = strict[0];\n return {\n matched: true,\n profile,\n properties: { linkedinUrl: profile.profileUrl, linkedinProviderId: profile.providerId },\n candidates: [],\n searched,\n };\n}\nconst rank = (r) => (r.nameMatches ? 2 : 0) + (r.companyInHeadline ? 1 : 0);\nconst candidates = rows\n .map((r, i) => ({ r, i }))\n .sort((a, b) => rank(b.r) - rank(a.r) || a.i - b.i)\n .slice(0, 5)\n .map(({ r }) => r);\nconst reason = !company ? 'name_only' : strict.length > 1 ? 'several' : strict.length === 1 ? 'more_results' : 'none';\nreturn { matched: false, reason, candidates, searched };\n"
338
338
  },
339
339
  {
340
340
  "name": "linkedin_get_profile",