Skip to content
Back to search

long-task-callback

SkillWorks with Claude CodeGitHub

Submit durable Codex, Claude, Pi or DeepSeek Harness child agents using registered task templates, or arrange callbacks for long-running commands, training, benchmarks, tests, builds and data jobs. Use when independent task ownership or a return to the original Codex, Claude Code, PI Agent or DeepSeek Harness session is needed. Repair LTC configuration status blocks; inspect results, ACK callbacks and continue the original goal.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked yesterday

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/lz59970062/long-task-wakeup with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/lz59970062/long-task-wakeup'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/lz59970062--long-task-wakeup/badge.svg)](/listings/lz59970062--long-task-wakeup)

HTML

<a href="/listings/lz59970062--long-task-wakeup"><img src="/api/listings/lz59970062--long-task-wakeup/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# 1. Install (stable release)
python3 -m pip install "git+https://github.com/lz59970062/long-task-wakeup.git@v0.7.0"

# 2. Install the skill for Codex + Claude Code and start the background daemon
ltc setup --force --enable --now
#    Using Pi too? Add --with-pi-extension (Pi skill + live-callback extension)
#    Using DeepSeek Harness too? Add --with-dsh (skill + launcher discovery)

# 3. Check that everything is healthy
ltc --version
ltc doctor --agent codex --session <session-id>

That's it. `setup` installs the bundled skill, so your agent already knows when and how to use `ltc`. From inside a Codex, Claude Code or DeepSeek Harness session, just ask it to run something long.

<details> <summary><b>Platform requirements</b></summary>

| Platform | Task owner | Coordinator | Notes | | --- | --- | --- | --- | | **Linux** | Independent systemd user service (v240+) | systemd user service | Falls back to GNU `screen` when no user systemd is available (e.g. Docker, AutoDL). See [containers](docs/containers.md). | | **macOS** | One-shot launchd job in the GUI session | LaunchAgent | No `screen` needed. See [macOS guide](docs/macos.md). | | **Windows 10+** | Per-user Task Scheduler task + Job Object | Login scheduled task | Requires a logged-in session and an ACL-capable filesystem (NTFS). See [Windows guide](docs/windows.md). |

The backend is recorded when a task is submitted and is never silently changed during recovery. To use the screen compatibility backend: `sudo apt install screen` (or `dnf install screen`), then `ltc run --backend screen ...`.

</details>

<details> <summary><b>Trying the 0.7.1 preview (Desktop callbacks)</b></summary>

`main` currently carries the **0.7.1 preview**, which adds explicit callback modes (`cli`, `codex-queue`, `manual`, `auto`). From a Codex Desktop session, `auto` delivers through the public `codex queue` command, so Desktop needs no launcher or restart.

# Installs from main and runs setup with the same interpreter
./scripts/install_from_git.sh https://github.com/lz59970062/long-task-wakeup.git
# Windows: scripts/install_from_git.ps1 -RepoUrl https://github.com/lz59970062/long-task-wakeup.git

Read [callback modes](docs/callback-modes.md) and [Codex Desktop](docs/integrations/desktop.en.md) for the states and limits: verified with real Codex on Linux; a real Desktop app, macOS and Windows have not been run.

</details>

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 744 lines
  1. ---
  2. name: long-task-callback
  3. description: Submit durable Codex, Claude, Pi or DeepSeek Harness child agents using registered task templates, or arrange callbacks for long-running commands, training, benchmarks, tests, builds and data jobs. Use when independent task ownership or a return to the original Codex, Claude Code, PI Agent or DeepSeek Harness session is needed. Repair LTC configuration status blocks; inspect results, ACK callbacks and continue the original goal.
  4. ---
  5. # Long Task Callback
  6. ## Rule
  7. Use an explicit callback when requested or when a command may outlive the current Codex or Claude
  8. Code turn.
  9. There are three public workflows:
  10. - `ltc run -- <command>` submits a new long-running task. The daemon launches it through an independent task owner (systemd on Linux, launchd on macOS, Task Scheduler on Windows; screen fallback on Linux/macOS).
  11. - `ltc agent codex|claude|pi|dsh -- <prompt>` submits a fresh child agent through the same durable
  12. lifecycle. Codex/Claude are available since `0.6.5`; Pi is a child worker and callback
  13. parent in the current preview.
  14. - `ltc done ...` queues a completion callback for work already owned by screen, tmux,
  15. Slurm, another scheduler, or an existing script.
  16. Daemon handoff is unconditional and requires no opt-in flag. Never add `--via-daemon` to newly
  17. written commands; old scripts may still pass it as a hidden no-op compatibility flag. Do not
  18. invent another public launch flag or a direct-mode flag. Do not use a direct recursive
  19. `codex exec resume` or `claude -p --resume` call from an agent tool sandbox. Do not let callback
  20. behavior change the task's original exit code unless the user explicitly requests `--strict`.
  21. ## Registered task templates
  22. `ltc template register NAME --file /path/to/template.yaml` installs a user template,
  23. copies its system-prompt dependencies, and creates a short `ltc-NAME` discovery skill.
  24. The YAML's `worker` and `description` describe the capability; CLI options can supply
  25. or override them. `ltc template list --json` shows the registered capabilities.
  26. The generated entrypoint binds the installed template file so another workspace's
  27. `LTC_TEMPLATE_DIR` cannot select a different same-named template. Keep Agent profile
  28. settings and the current parent's callback binding.
  29. Read the matching entrypoint and pass actual task scope, target paths and evidence
  30. constraints. Check readiness with `ltc doctor --operation agent --agent-worker WORKER`
  31. and validate submission with `--dry-run` when needed. Routine local edits need not be
  32. delegated. On completion, inspect the real result and edits, ACK and continue.
  33. Registration maintains only the following index; preserve the surrounding instructions.
  34. <!-- ltc:registered-templates:begin -->
  35. <!-- ltc:registered-templates:end -->
  36. ## Callback rules that always apply
  37. ### Callback modes (0.7.1 preview)
  38. `--callback-mode auto` recognizes the current Codex Desktop origin marker and
  39. selects `codex-queue`; other origins select `cli`. Use an explicit mode if the host
  40. omits that marker. A historical session source is not its current owner.
  41. `codex-queue` runs the public `codex queue --thread UUID --message TEXT` once with
  42. the submitting session's environment. It needs no launcher, shared Core or restart,
  43. and never falls back to a second writer. A Codex without that command refuses a new
  44. `run` or `agent` before task admission. `done` still preserves completed work.
  45. A queued message is not a received one. The callback stays pending until the chat
  46. runs its ACK, and `ltc status` says it is waiting. It does not hold back later
  47. callbacks for that thread. The ACK runs under the chat's own permissions: if the
  48. sandbox blocks it, request approval to run the same command. Nothing is sent again.
  49. A rejection (`codex queue` reported an error, or could not start) is in `failed`
  50. with the cause: fix it, then `ltc retry --id ID`. A kill, timeout or unreadable
  51. success is an unknown outcome and retry is refused, because the message may be in
  52. the chat: inspect the chat, then `ltc ack` or `ltc cancel`. Never resend it by hand.
  53. `manual` explicitly saves results/callbacks for later receipt and does not start
  54. an Agent automatically. Choose it only when the user accepts this limitation.
  55. The Desktop launcher is retired: `--callback-mode desktop` is refused for new work,
  56. `ltc desktop` only explains the replacement, and setup generates no launcher. A saved
  57. `desktop` callback keeps its results and route; if it is blocked, move it with
  58. `ltc retry --id ID --callback-mode codex-queue`, which does not rerun the workload.
  59. Read `doctor`'s separate `callback` field. `owner_reachable` is a read-only
  60. observation, not proof of end-to-end receipt. Sandboxed tools may need authorized
  61. ordinary-user execution to inspect native peers; never weaken identity checks.
  62. After repairing a known failed handoff, `ltc retry --id ID`
  63. requeues the original callback without rerunning its workload. Unknown submission
  64. outcomes, active deliveries, ACKs and cancellations prevent ordinary retry.
  65. Inspect manual results in the bound session before ACK, and label that receipt
  66. as manual rather than a successful autonomous callback test.
  67. Upgrade the coordinator before using new task records v3 and v6 / callback records
  68. v2 and v5. Older daemons deliberately reject them instead of dropping callback-mode
  69. intent, and keep the record; `ltc retry` delivers it after the upgrade.
  70. On every callback, inspect the result and relevant artifacts, decide whether the
  71. original goal is complete, blocked, or needs another action, and continue when the
  72. next step is clear and safe. Inspect existing work before relaunching it. Then run
  73. the supplied ACK command; ACK confirms receipt, not completion of the overall goal.
  74. Resume only the bound conversation, never redirect to `--last` or another session.
  75. Read the user callback hook at initial LTC use when present. Its instructions still
  76. apply when not repeated. Since LTC 0.6.6, standard reminders appear on the first callback and every
  77. 4 distinct callbacks thereafter; user-hook reminders on the first and every 3.
  78. A short callback omits repeated prose, not these responsibilities. Task results,
  79. routing and the ACK command remain present. In 0.7.0, full commands, timestamps and handoff text are saved at the supplied Details path. Read that file before acting when the envelope says so; otherwise inspect relevant result artifacts directly. An exit code is process status, not proof of test success.
  80. When reporting a callback to the user, include the recorded task runtime in one
  81. short phrase when available, such as `Finished in 2m 5.5s`. Use execution duration,
  82. not the time spent waiting for delivery; do not invent a duration when it is unknown.
  83. Configure with `ltc prompt-policy --system-every 4 --user-every 3`; no options shows
  84. the effective policy. `1` means every callback. The file is
  85. `${LTC_HOME:-~/.ltc}/callback-prompts.yaml`. Counters are per
  86. queue, agent and bound session, allocated at first delivery attempt. Retries reuse
  87. the same sequence and reminder decisions across restarts. Queuing/dry-run does not
  88. count. An unsafe `--last` target keeps full reminders because its identity is unknown.
  89. ## Ownership invariant
  90. The 0.7 topology separates the coordinator and task owners:
  91. ```text
  92. systemd user service / macOS LaunchAgent / Windows login task -> ltc daemon (recovery and callbacks)
  93. independent systemd service / launchd job / Windows scheduled runner -> LTC worker -> command / child agent
  94. ```
  95. `--backend auto` prefers an available systemd user manager (v240+) on Linux or
  96. the logged-in GUI launchd domain on macOS, otherwise screen on those platforms.
  97. On Windows it selects `windows-task`, using Task Scheduler in the logged-in user
  98. session and a runner-owned Job Object. `--backend systemd`, `--backend launchd`
  99. or `--backend windows-task` requires that native manager; `--backend screen` explicitly
  100. selects the compatibility backend. Existing screen tasks retain their owner. The
  101. native backend needs no screen. A screen process can remain inside its launching
  102. service's control group: do not assume it survives stopping that service.
  103. After submission, record the task ID, execution backend and artifact paths, then
  104. return control when no independent work remains. For long work, avoid polling
  105. processes or logs on a timer. Live monitoring is appropriate when requested or
  106. diagnosing callback infrastructure. Do not change a running task's owner or
  107. automatically retry an unknown native launch. DSH callbacks are live-only and use
  108. the same native launch path as the other agents.
  109. ## Duration policy
  110. Choose the execution path before launching the command:
  111. - If the command is reliably expected to finish within 60 seconds, one foreground wait is
  112. acceptable.
  113. - If it may take about one minute or longer, its duration is uncertain, or a second status check
  114. might be needed, use `ltc run` from the start.
  115. - Do not keep a prompt cache warm by polling. A few-minute task should normally use callback
  116. delivery: the daemon and screen wait without model turns, then resume the same conversation
  117. when work completes; ACK and existing-artifact checks handle possible duplicate delivery.
  118. - If intermediate results genuinely require agent decisions, use sparse milestone callbacks
  119. rather than timer-based status polling.
  120. If a supposedly short foreground command unexpectedly remains active, keep the current turn
  121. responsible for it; do not abandon it as an agent-owned background process.
  122. The command name is `ltc`; `codex-long-task-wakeup` remains a compatibility alias.
  123. ## Install
  124. ### Automatic configuration checks
  125. `ltc run`, `ltc agent` and `ltc done` automatically check LTC's supported environment,
  126. configuration and observed runtime chain: storage, coordinator, recorded task
  127. owners, saved results and callback handoff. These checks follow the selected
  128. platform adapter and each task's recorded backend, not a fixed list of software
  129. to install on every host.
  130. Healthy calls add no diagnostic text. A failed check appends a JSON block between
  131. `[ltc-status]` and `[/ltc-status]` on stderr. This is an action request to the
  132. **calling Agent**: diagnose the listed issues, configure LTC in the current
  133. environment, run its `recheck_command`, then continue the user's task. Do not hand
  134. ordinary installation, service startup or configuration commands back to the user.
  135. The block supplies `repair_command` and `recheck_command` as argument arrays pinned
  136. to the current LTC installation and queue. Address missing prerequisites first;
  137. preserve the original Agent session, profile paths and existing custom settings.
  138. Read `environment`, `checks.configuration`, `checks.runtime` and each issue's
  139. `kind`/`code` to distinguish missing setup from a runtime fault or unsupported OS.
  140. `repair_command` can be null: an absent task owner or unresolved delivery needs
  141. artifact/session inspection and lifecycle recovery, not a generic reinstall.
  142. Windows checks Task Scheduler, private state and coordinator identity; macOS checks
  143. launchd/screen readiness. Repair commands follow the selected platform and queue.
  144. The setup repair uses `--keep-skill` to retain an installed skill while installing
  145. one when missing. It can update the LTC coordinator configuration; inspect existing
  146. service customizations before doing so. Never replace a missing binding with an
  147. invented session or `--last`.
  148. For `done`, repair adds `setup --callback-only`: externally owned work needs the
  149. callback coordinator, not a local business-task execution backend.
  150. Check `work.state` before retrying: `task_persisted` or `callback_queued` means
  151. repair the infrastructure around that existing ID, **do not submit it again**.
  152. For `unknown`, inspect that ID's task/queue records before deciding whether a retry
  153. is needed. For `not_submitted`, retry the original LTC invocation only after the
  154. prerequisites pass. A `done` invocation reports work already performed; repair or
  155. retry its callback without rerunning that work.
  156. Use `ltc doctor` for an explicit JSON check (exit 0 for local readiness, 1 for
  157. configuration needed). Pass the same queue, backend and session options; for a
  158. child task include `--operation agent --agent-worker <agent>`. Readiness checks
  159. local state and observed liveness, not task progress, authentication, the
  160. coordinator's environment or end-to-end session delivery. An idle queue needs no
  161. screen session; a durable task result takes precedence over a vanished owner.
  162. An unavailable owner query is unknown, not proof of a dead task. Saved results
  163. without callback handoff after a short grace period and unacknowledged failed
  164. deliveries need attention; acknowledged/canceled history does not. After each
  165. repair, recheck and use the new evidence. If a repair
  166. does not resolve its issue, investigate rather than repeat it unchanged. Ask the
  167. user only for an indispensable login/authorization or unavailable information,
  168. with the specific blocker; do not ask them to perform routine configuration.
  169. Checks do not change command exit semantics, install software or start services
  170. themselves. Help, dry-runs, private workers and ACK/cancel paths remain available
  171. without this automatic check.
  172. ```bash
  173. # Install screen only if using the compatibility backend.
  174. python3 -m pip install "git+https://github.com/lz59970062/long-task-wakeup.git@codex/macos-desktop-callback"
  175. ltc setup --force --enable --now
  176. ```
  177. `setup` installs this skill for Codex and Claude Code and configures the selected coordinator service. Add `--with-dsh` to also install it for DeepSeek Harness; `--with-pi-extension` adds Pi. It requires a reachable native manager (systemd/launchd/Task Scheduler) or screen for the Linux/macOS compatibility backend. It creates the user-editable fixed prompt hook at
  178. `${LTC_HOME:-~/.ltc}/callback-hook.md` without overwriting existing content.
  179. The delivery worker reads that UTF-8 file on attempts whose saved user-reminder decision is
  180. due, so edits apply on the next due attempt without a restart. Non-empty content is appended
  181. under `[long-task-callback-user-hook]`; hook read failures warn and continue with the callback.
  182. `setup` also checks for the Claude Code CLI and runs `claude auth status` with output suppressed.
  183. This check is advisory and must not block Codex-only installation or print credentials/account
  184. details. Claude configuration must be present in the shell that later submits `ltc agent claude`.
  185. ## Windows
  186. Use Windows 10+, Python 3.9+, an ACL-capable local filesystem such as NTFS, and
  187. the ordinary logged-in user's Task Scheduler session. `--backend auto` and
  188. `--service auto` select `windows-task`; screen and WSL are unnecessary. Install
  189. from the release checkout in PowerShell without activating the venv:
  190. ```powershell
  191. git clone --branch codex/macos-desktop-callback --depth 1 https://github.com/lz59970062/long-task-wakeup.git
  192. Set-Location long-task-wakeup
  193. py -3 -m venv .venv
  194. & .\.venv\Scripts\python.exe -m pip install .
  195. & .\.venv\Scripts\ltc.exe setup --service windows-task --force --enable --now
  196. ```
  197. Keep the installed runtime at its fixed path. Setup pins the Agent profiles,
  198. executables, PATH and queue in a private configuration file. One Agent profile
  199. has one coordinator queue. For another queue, use a separate profile, or drain
  200. the current tasks and callbacks, run `ltc uninstall-windows-task`, then reinstall
  201. for the new queue. Do not copy another machine's session binding.
  202. Use native argument lists. Recognized npm/forwarding `.cmd` launchers are resolved
  203. without a shell; unsupported wrappers require their underlying executable.
  204. Windows callbacks default to CLI resume of the actual original session. Execute the callback's emitted
  205. PowerShell ACK verbatim, including its leading `&` and quoted paths. ACK confirms
  206. receipt only, not goal completion. Never replace the target with `--last`.
  207. On Windows, Desktop sessions use `codex-queue` like any other platform (not yet run
  208. natively). A live Windows test with Codex 0.153.4 could not resume its open Desktop session:
  209. the CLI reported `already has an active writer`. Ending an Agent turn does not
  210. guarantee that Desktop releases this owner. Preserve the failed callback and
  211. report this transport limitation or move it to `codex-queue`; do not delete Codex's writer lock, forge an
  212. ACK, change the bound session or rerun the business work. Native workload and
  213. fake-Agent delivery tests do not establish live original-session receipt.
  214. New private files/directories grant only the current user and SYSTEM access.
  215. Do not weaken those ACLs to work around an Agent sandbox's restricted token;
  216. authorized native setup/tests may need an ordinary user process outside that
  217. sandbox. Flushed file data and write-through replacement do not provide a
  218. POSIX directory-fsync guarantee: namespace changes may be lost after sudden
  219. power failure. Login is required; sleep pauses work and logout/reboot can
  220. interrupt it. Missing owners and unknown launches never authorize auto-replay.
  221. Use `ltc install-windows-task --print` for the public registration preview,
  222. `ltc doctor --backend windows-task` with the original session and queue for
  223. diagnosis, and `ltc setup --service windows-task --keep-skill --force --enable --now`
  224. after upgrading. A verified coordinator waits for deliveries to drain before
  225. its supervisor replaces it. `ltc uninstall-windows-task` removes the login
  226. registration and drains the coordinator; it does not stop business tasks or
  227. erase results/ACKs. Do not delete lock files while inherited delivery handles
  228. may still own them. See the repository's `docs/windows.md` and validation record.
  229. ## macOS
  230. `ltc setup --force --enable --now` selects a user LaunchAgent in the logged-in GUI
  231. session and independent one-shot launchd jobs for new tasks. Screen is optional.
  232. Use `ltc install-launchd --print` to preview the plist, `--backend launchd` to
  233. require the native task owner, or `--backend screen --service standalone` for
  234. headless sessions without a GUI domain. Apple's bundled screen is supported.
  235. Task plists live in private task directories, never in login startup directories.
  236. They have no KeepAlive/restart policy. A coordinator restart does not restart the
  237. task. Sleep pauses work; logout and reboot can interrupt it. Never replay a saved
  238. task automatically. Setup requests identity-verified reload after deliveries drain;
  239. new LaunchAgent environment/arguments take effect on the next service load.
  240. Native process/service access may require an ordinary terminal outside an Agent
  241. tool sandbox. Preserve the original queue/session and inspect any persisted work
  242. before repeating submission. Desktop socket delivery uses local peer credentials;
  243. CLI delivery is the fallback when the optional socket is unavailable.
  244. ```bash
  245. launchctl print "gui/$(id -u)/codex-long-task-wakeup"
  246. tail -f "${LTC_HOME:-$HOME/.ltc}/daemon.log"
  247. ```
  248. ## Containers (Docker / AutoDL)
  249. Use `--backend screen` where no systemd user manager is available. Install screen
  250. in the container. Run LTC, the Agent CLI and workload as the same user inside the
  251. same container with durable local state/workspace mounts. Agent CLI and credentials
  252. must be available inside that container; the host's desktop socket is not assumed.
  253. `ltc setup --backend screen --service standalone --now` starts a coordinator in an
  254. existing AutoDL/container session without systemd. `--service auto` selects systemd
  255. when reachable, otherwise standalone. Use `--service supervisor` only when explicitly
  256. managing that configuration. Standalone `--enable` cannot register container startup.
  257. For Docker images, run `ltc daemon` in foreground under `docker --init`, or use an
  258. external supervisor. A container CMD must not merely spawn a background daemon and exit.
  259. When setting up unattended container use, guide the user through the startup route
  260. appropriate to their platform: a verified AutoDL boot hook invoking standalone
  261. setup with `--keep-skill --now`, an existing administered Supervisor running
  262. `ltc daemon` with `autostart`/`autorestart`, or a foreground Docker daemon with
  263. `--restart unless-stopped`. Inspect the actual startup mechanism; creating
  264. `/root/autodl.sh` alone does not establish that an image executes it. AutoDL elastic
  265. deployment main commands must stay in the foreground. Preserve existing boot-hook
  266. commands, Agent profiles, queue paths and service customizations. Pin executable
  267. paths and runtime environment instead of relying on interactive Conda/NVM setup.
  268. For custom Supervisor layouts, use its verified configuration with `supervisorctl
  269. -c`; LTC's built-in installer uses bare control commands and an unscoped update.
  270. Choose one startup owner per queue and distinguish boot startup from crash recovery.
  271. Prepare changes within the user's authorized scope; guidance alone does not authorize
  272. restarting a busy container or replacing platform services. Detailed examples and
  273. removal steps are in the repository's `docs/containers.md`.
  274. After configuration, check the service and `ltc doctor` under the same profile, then
  275. verify startup at a planned idle container restart and a real original-session
  276. callback/ACK. Report any untested restart behavior explicitly. Coordinator autostart
  277. does not preserve or authorize replay of an interrupted business process.
  278. Terminal disconnection or standalone coordinator exit can leave screen tasks alive
  279. while the container remains running. If the coordinator is the container's main
  280. process, its exit ends the container as well. Container stop/recreation interrupts
  281. work; inspect persisted results/checkpoints and session identity before resubmitting.
  282. ## Run: submit new work
  283. Use this when the agent is launching the long command:
  284. ```bash
  285. ltc run \
  286. --cwd "$PWD" \
  287. --task "train model" \
  288. -- python train.py --config configs/exp.yaml
  289. ```
  290. The submission is durable before the command returns. Record the printed values. Use the reported log/result paths for either backend. For screen-owned tasks, the
  291. inspection commands are:
  292. ```bash
  293. screen -ls
  294. screen -r ltc-<task-id>
  295. tail -f ~/.ltc/tasks/<task-id>/attempt-1.log
  296. ```
  297. Detaching with `Ctrl-a d` leaves the task running.
  298. ## Agent: submit a durable fresh child agent
  299. Use `ltc agent` when a fresh Codex, Claude Code, Pi or DeepSeek Harness process should perform an independent task and
  300. the work needs independent ownership, durable artifacts, or a completion callback. For short work that
  301. fits an in-turn native subagent, LTC is unnecessary.
  302. ```bash
  303. ltc agent claude \
  304. --cwd "$PWD" \
  305. --task "review parser edge cases" \
  306. -- "Inspect parser.py and its tests. Report concrete defects and suggested fixes."
  307. ltc agent codex \
  308. --cwd "$PWD" \
  309. --task "implement parser fixes" \
  310. -- "Fix the confirmed parser defects and run the relevant tests."
  311. ltc agent pi \
  312. --cwd "$PWD" \
  313. --task "review parser edge cases" \
  314. -- "Inspect parser.py and its tests. Report concrete defects and suggested fixes."
  315. ```
  316. The `codex|claude|pi|dsh` subcommand selects the child process. The existing `--agent` option still
  317. selects the parent agent to wake when explicit callback binding is needed. The text after `--` is
  318. the child's task, not a shell command. State the objective, relevant paths or context, expected
  319. deliverable, and real constraints; do not impose a fixed task template when they are unnecessary.
  320. LTC snapshots the launching environment and prepares a fresh child environment. For Claude Code,
  321. use `ltc agent claude` instead of manually wrapping `claude -p` with `ltc run`: agent mode keeps
  322. the launching configuration, authentication, proxy, and custom environment while removing parent
  323. session markers that prevent a clean child launch. Do not put credentials in the task prompt, and
  324. do not add `--bare` by default.
  325. Before the first Claude child, confirm `command -v claude` and `claude auth status`. Do not require
  326. `ANTHROPIC_API_KEY` specifically: OAuth/keychain and supported cloud providers are valid too. When
  327. used, `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL`, `CLAUDE_CONFIG_DIR`, proxy/certificate settings,
  328. and other custom values must be available in the submission environment; never print their values.
  329. For Pi, use `ltc doctor --operation agent --agent-worker pi` to check child readiness.
  330. `LONG_TASK_WAKEUP_PI_BIN` overrides the executable. LTC runs
  331. `pi --print --mode text --no-session` with prompt stdin and captures assistant text
  332. in the managed private result artifact. Keep the submission-time Pi profile,
  333. authentication, API, proxy and extension configuration; remove Codex/Claude parent
  334. markers plus `PI_SESSION_ID`, `PI_SESSION_FILE` and `PI_CODING_AGENT`. Do not put
  335. credentials in prompts or persist a child session.
  336. `--model` accepts Pi's model notation, including `provider/model`; `--reasoning-effort`
  337. maps to `--thinking` and accepts `off`, `minimal`, `low`, `medium`, `high`, `xhigh`,
  338. and `max`, but rejects `ultra`. Tool permissions and project extension trust follow
  339. Pi's noninteractive configuration; do not add `--approve`. LTC's `--sandbox-mode`
  340. is Codex-only and `--permission-mode` is Claude-only. Pi 0.87.1's CLI contract was
  341. checked; native Windows/macOS Pi launch has not been verified in this session.
  342. A Pi session can also be a callback parent (`--agent pi`). Pi gets its own installed
  343. skill for that workflow; from Codex or Claude Code only the `ltc agent pi` child applies.
  344. Pi accepts `--system-prompt-file ./prompts/pi-system.md` before `--`. Keep this
  345. separate from `--template`/`--template-file`, which build the stdin task prompt.
  346. Pi's `--system-prompt` receives the snapshot and replaces its built-in base system
  347. prompt while retaining normal project context, skills and appended instructions.
  348. A relative CLI file path uses the submitting shell directory, independently of
  349. child `--cwd`. Read a nonempty UTF-8 source at submission and snapshot it privately
  350. as `agent-system-prompt.md`; later edits/deletion must not change queued tasks.
  351. No interpolation or script evaluation occurs. `--dry-run` reports the resolved
  352. source without creating task files or starting the child. The flag is Pi-only.
  353. LTC owns the private prompt and result files in the managed task directory. The caller does not
  354. choose those paths. On callback, inspect the child result and relevant artifacts, acknowledge the
  355. callback, and continue the original goal when the next action is clear.
  356. ## Done: report externally managed work
  357. When editing an existing script, shell trap, Python `finally`, or scheduler epilogue, use:
  358. ```bash
  359. set +e
  360. python train.py --config configs/exp.yaml
  361. status=$?
  362. ltc done \
  363. --cwd "$PWD" \
  364. --task "train model" \
  365. --command "python train.py --config configs/exp.yaml" \
  366. --exit-code "$status"
  367. exit "$status"
  368. ```
  369. `done` only queues delivery. It does not make the preceding task durable. Confirm that an external
  370. process manager already owns that task.
  371. Python pattern:
  372. ```python
  373. import subprocess
  374. status = 1
  375. try:
  376. status = subprocess.call(["python", "train.py", "--config", "configs/exp.yaml"])
  377. finally:
  378. subprocess.call([
  379. "ltc", "done",
  380. "--cwd", "/path/to/project",
  381. "--task", "train model",
  382. "--command", "python train.py --config configs/exp.yaml",
  383. "--exit-code", str(status),
  384. ])
  385. ```
  386. ## Session binding
  387. Run from the agent-owned environment and omit target flags by default. LTC detects
  388. `CODEX_THREAD_ID`, `CLAUDE_CODE_SESSION_ID`, or Pi's absolute `PI_SESSION_FILE` (an ID alone is insufficient).
  389. Use `--agent codex|claude|pi|dsh --session <id>` when explicit binding is necessary. DSH callbacks are delivered only to a live session by `ltc wait`; DSH has no headless fallback. For Pi,
  390. prefer the absolute session file from `PI_SESSION_FILE`. Use `--last` only as
  391. an unsafe manual fallback; it always warns. If the target cannot be determined, fail instead of
  392. guessing.
  393. ## Restart recovery
  394. ### Daemon restart
  395. For native tasks, the independent systemd unit, launchd job or Windows scheduled
  396. runner owns the worker. Restarting the
  397. coordinator should not restart that task. If querying the owner fails, its state
  398. is unknown; never treat a manager connection failure as permission to relaunch.
  399. A saved result takes precedence over owner visibility. Reconstruct a missing
  400. callback with the same ID. Old screen records use their original recovery path.
  401. ### Worker startup handshake
  402. For the legacy screen backend, a launched worker must durably move its task from `launching` to `running`. Allow a
  403. one-second handshake window. If screen disappears first, record the failed launch and retry no
  404. more than three total attempts with exponential backoff. After the final failure, set
  405. `launch_failed`, remove the launch credentials, queue exactly one recovery callback, and never
  406. automatically relaunch that task. Generate worker tokens with an `ltc_` prefix and pass them only
  407. as a single `--token=value` argument. Treat a legacy `launching` record without an attempt counter
  408. as an unknown prior launch failure and never automatically retry it during upgrade.
  409. Native systemd/launchd/Windows launches with ambiguous outcomes are not retried automatically,
  410. even if no unit is visible. Inspect the task record and outputs.
  411. ### Same-host reboot
  412. No backend preserves the running process across a host reboot. Never automatically rerun the command and do not add a
  413. `--resume-command` mechanism. Restore the originally bound Codex or Claude Code conversation with
  414. the task id, screen name, log path, interruption reason, and available checkpoint/artifact context.
  415. The restored agent must:
  416. 1. inspect local logs, outputs, processes, manifests, and checkpoints;
  417. 2. supplement the completed status if durable artifacts prove completion;
  418. 3. otherwise recreate the task through the normal `ltc run` workflow from a valid
  419. checkpoint;
  420. 4. or record the exact blocking condition.
  421. ### Cross-host recovery
  422. Do not attempt it. LTC does not transfer code, data, environments, checkpoints, credentials, or
  423. compute resources between hosts.
  424. ## Callback acknowledgement
  425. The callback prompt includes:
  426. ```bash
  427. ltc ack --queue-dir <queue-dir> --id <callback-id>
  428. ```
  429. After inspecting the result and choosing whether to continue, stop, or ask, run that command.
  430. Acknowledgements are monotonic. Missing ACKs retry with backoff. Delivery is at-least-once, so
  431. always inspect existing processes and artifacts before starting follow-up work.
  432. An ACK marker immediately ends completion-stream waiting and releases the delivery lease; it must
  433. not wait for a separate Desktop App Server `turn/completed` notification.
  434. The resumed agent needs write access only to the callback queue. A normal ACK must not create or
  435. modify global target-lock files; if a rare retained lease needs cleanup, the daemon reconciles it
  436. after the durable ACK marker appears.
  437. Use `--callback-format full` at submission only when full inline detail is needed.
  438. The default compact format archives the complete original callback privately and
  439. omits recurring counter explanations. System/user reminder cadence remains 4/3;
  440. user-hook text is preserved on its scheduled callbacks.
  441. Callback ACK confirms one delivery only. It must never implicitly complete a persistent goal.
  442. ## Goal acknowledgement and automatic inquiry
  443. Every multi-stage goal must use a mutable UTF-8 YAML goal plan. Treat that file as the single
  444. source of truth for the current overall goal and its ordered path, not the task text remembered
  445. from an earlier turn. Use this schema:
  446. ```yaml
  447. version: 1
  448. revision: 1
  449. goal: Release version 0.6.2
  450. path:
  451. - id: implement
  452. title: Implement the change
  453. status: completed
  454. evidence: tests/test_feature.py
  455. - id: verify
  456. title: Run tests and inspect the result
  457. status: in_progress
  458. - id: publish
  459. title: Publish the release
  460. status: pending
  461. amendments:
  462. - revision: 1
  463. reason: Initial path
  464. ```
  465. Statuses are `pending`, `in_progress`, `blocked`, and `completed`. Completed items must form a
  466. continuous prefix of `path`; there may be at most one `in_progress` or `blocked` item, and it must
  467. be the first unfinished item.
  468. The plan is intentionally editable. The user or agent may revise later path items, reopen an
  469. earlier item, append or remove items, or change the overall `goal`. Increment `revision` and record
  470. the reason in `amendments` when the intended path changes. After each item, update its status and
  471. evidence. Always follow the latest valid file; do not preserve an obsolete path from memory.
  472. Workflow:
  473. 1. Create it once:
  474. ```bash
  475. ltc goal start --id <goal-id> --session <session-id> --cwd "$PWD" \
  476. --task "..." --plan-file path/to/goal-plan.yaml
  477. ```
  478. 2. Bind each `run` or `done` callback with `--goal-id <goal-id>`.
  479. 3. Before saying or implying that the whole goal is complete, check the latest plan:
  480. ```bash
  481. ltc goal check --id <goal-id>
  482. ```
  483. Inspect the actual work and artifacts against every path item. This command reports the
  484. current item, remaining path, and the current plan SHA-256.
  485. 4. Only if every item, including the final item, is confirmed `completed`:
  486. ```bash
  487. ltc goal ack --id <goal-id> --state completed --plan-sha256 <checked-sha256>
  488. ```
  489. 5. If progress requires a specific missing condition:
  490. ```bash
  491. ltc goal ack --id <goal-id> --state blocked_conditions \
  492. --condition "specific prerequisite"
  493. ```
  494. 6. When that condition is met:
  495. ```bash
  496. ltc goal resume --id <goal-id>
  497. ```
  498. The completion gate rejects an unchecked plan, a stale digest, an invalid/nonsequential path, or
  499. any unfinished item. Editing the YAML invalidates an earlier check, so the agent must reread the
  500. new overall goal and path. Completion is terminal. A callback ACK does not count as goal
  501. completion.
  502. For an active goal created before YAML plans were required, or to move a plan file, attach the
  503. latest plan and then check it again:
  504. ```bash
  505. ltc goal set-plan --id <goal-id> --plan-file path/to/goal-plan.yaml
  506. ltc goal check --id <goal-id>
  507. ```
  508. ### Plan file lifecycle and user agreement
  509. - Use one plan file for one independent goal. Prefer a stable project-local path such as
  510. `.ltc/goals/<goal-id>.yaml`. Never recycle a completed goal's file for another goal.
  511. - Before `goal start`, derive the overall goal, acceptance conditions, and ordered path from the
  512. user's request, then create the YAML. For a clear, conventional, low-risk path, create it and
  513. tell the user its location and main items without waiting for another approval. If the path
  514. requires a strategic choice, materially different resource use, changed acceptance criteria,
  515. or another consequential tradeoff, agree on those points with the user before starting.
  516. - Keep using the same file when the goal is blocked, resumed, or revised. The user may edit it at
  517. any time; their latest valid revision overrides the agent's remembered path. A follow-on
  518. objective after terminal completion is a new goal with a new file.
  519. - After completion, preserve the YAML at its recorded path as the audit record. Do not delete it
  520. automatically. If the user wants it under an archive directory, move it while the goal is still
  521. active, run `goal set-plan` with the archive path, and then perform the final `goal check` and
  522. completion ACK.
  523. After three hours without a newly queued ordinary callback, the daemon automatically restores the
  524. same conversation and asks it to continue, ACK completion, or state the exact blocking condition.
  525. The inquiry repeats until the goal is completed or blocked. Reboot recovery callbacks follow the
  526. same goal rules and do not disable this inquiry.
  527. ## Multi-round behavior
  528. After each wakeup, inspect relevant logs, metrics, checkpoints, reports, and outputs. Decide:
  529. ```text
  530. current_goal:
  531. last_result:
  532. decision: continue | stop_success | stop_blocked | ask_user
  533. reason:
  534. next_command:
  535. budget_remaining:
  536. ```
  537. Continue only when the next action is clear, low-risk, aligned with the same goal, and within the
  538. user's budget and project rules. Ask before expanding resource use, changing the scientific or
  539. product objective, deleting artifacts, or making a strategic tradeoff.
  540. When stopping, summarize what was attempted, what changed, and the smallest decision or resource
  541. needed from the user.
  542. ## Daemon operations
  543. The systemd user service (Linux), LaunchAgent (macOS), or login scheduled task
  544. (Windows) keeps `ltc daemon` available
  545. for submissions, recovery, and callbacks. On Linux:
  546. ```bash
  547. systemctl --user status codex-long-task-wakeup.service
  548. journalctl --user -u codex-long-task-wakeup.service -f
  549. ```
  550. The daemon watches `${LTC_HOME:-~/.ltc}/queue` by default. Use `--queue-dir`
  551. or `CODEX_LONG_TASK_WAKEUP_QUEUE_DIR` for an explicit queue.
  552. Before restarting a service or container, drain live callback deliveries where possible.
  553. Unacknowledged interrupted delivery is eligible for replay.
  554. Cancel callbacks through the CLI rather than deleting state:
  555. ```bash
  556. ltc cancel --id <callback-id>
  557. ltc cancel --queue-dir <queue-dir> --all --message "no longer needed"
  558. ```
  559. `cancel` cancels callbacks only; it does not terminate a running workload.
  560. ## Independent test authoring preset
  561. Use `ltc agent codex --template test --task "write independent tests" -- "Requirements and specification paths"`
  562. when a separate agent should author tests for the parent to execute. The default Codex model is
  563. `gpt-5.6-luna` with `max` reasoning; override using `--model` and `--reasoning-effort`.
  564. These flags affect the child only; `--agent` continues to select the parent callback agent.
  565. Claude supports the template and `--model`, inherits its own model by default, and rejects
  566. `--reasoning-effort`. Pi supports the same prompt and handoff, inherits its own model/thinking
  567. configuration unless overridden, and accepts the thinking levels listed above. The built-in
  568. Codex model/effort defaults never apply to Pi. Put all flags before `--`; provide concrete requirements after it.
  569. The child writes requirement-derived tests and a handoff, without running tests or modifying
  570. production code. The parent reviews the changed files, requirements and commands, then runs
  571. the tests and reports actual results. Child completion is not a passing-test result. Diagnose
  572. failed/empty/partial handoffs before execution; never weaken assertions merely to get green.
  573. The shared workspace is not isolated: these are prompt constraints, so inspect actual changes.
  574. Use `--dry-run` to inspect the expanded prompt and resolved model before submission.
  575. ## User-defined child templates
  576. Load `--template NAME` from `${LTC_TEMPLATE_DIR}` when set, otherwise
  577. `${XDG_CONFIG_HOME:-~/.config}/ltc/templates/NAME.yaml` (or `.yml`), or use
  578. `--template-file PATH` for an explicit file. These options are mutually exclusive.
  579. A relative file path uses the submitting shell directory, not the child's `--cwd`.
  580. Template names/filename stems start with a letter or digit and otherwise use only
  581. letters, digits, underscores and hyphens. No reinstall is needed when files change.
  582. YAML requires `version: 1` (positive integer revision) and non-empty `prompt: |` text.
  583. Optional `codex: {model: gpt-5.6-luna, reasoning_effort: max}` and
  584. `claude: {model: sonnet}` set worker-specific defaults; Pi also accepts
  585. `pi: {model: provider/id, reasoning_effort: high}`. CLI options take precedence.
  586. Optional `pi: {system_prompt_file: prompts/system.md}` loads a separate nonempty
  587. UTF-8 system prompt; its relative path uses the YAML directory. An explicit
  588. `--system-prompt-file` overrides it and resolves relative to the submitting shell.
  589. Optional `handoff: |` text instructs the parent on callback. No variable interpolation
  590. or code evaluation occurs. Unknown/duplicate fields or invalid values fail before
  591. submission. Use `--dry-run` to inspect source, prompt, defaults and handoff.
  592. A same-named user template replaces the entire built-in profile, including its
  593. callback guidance; a custom `test` must supply its own test handoff instructions.
  594. Do not silently fall back from a malformed user file to the built-in. Both `.yaml`
  595. and `.yml` existing for one name is an error. Submission freezes source, revision,
  596. prompt, model/effort and handoff, so edits do not alter queued work.
README.md · README · 346 lines
  1. <p align="center">
  2. <img src="./assets/readme/hero.svg" width="100%" alt="Long Task Callback (ltc): run a task under an independent Linux, macOS or Windows owner and wake the same Codex or Claude Code session when it finishes">
  3. </p>
  4. <h3 align="center">Stop babysitting long-running jobs. Let your agent sleep — and wake it up when the work is done.</h3>
  5. <p align="center">
  6. <a href="https://github.com/lz59970062/long-task-wakeup/tree/v0.7.0"><img src="https://img.shields.io/badge/stable-v0.7.0-3fb950" alt="Stable v0.7.0"></a>
  7. <a href="./CHANGELOG.md"><img src="https://img.shields.io/badge/preview-0.7.1a1-a371f7" alt="Preview 0.7.1a1"></a>
  8. <img src="https://img.shields.io/badge/python-%E2%89%A53.9-3776ab" alt="Python ≥ 3.9">
  9. <img src="https://img.shields.io/badge/platforms-Linux%20%C2%B7%20macOS%20%C2%B7%20Windows-58a6ff" alt="Linux, macOS, Windows">
  10. <img src="https://img.shields.io/badge/agents-Codex%20%C2%B7%20Claude%20Code%20%C2%B7%20Pi%20%C2%B7%20DSH-d29922" alt="Works with Codex, Claude Code, Pi and DeepSeek Harness">
  11. <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-lightgrey" alt="MIT license"></a>
  12. </p>
  13. <p align="center">
  14. <a href="#-quick-start">Quick start</a> ·
  15. <a href="#-how-it-works">How it works</a> ·
  16. <a href="#-usage">Usage</a> ·
  17. <a href="#-documentation">Docs</a> ·
  18. <a href="./README.zh-CN.md">中文</a>
  19. </p>
  20. ---
  21. ## The problem
  22. You ask Codex, Claude Code, Pi or DeepSeek Harness to train a model, run a benchmark, or build a big project. The job takes
  23. two hours. Now what?
  24. - The agent **polls** with `sleep && tail` — burning turns, tokens and context on nothing.
  25. - Or the job is **owned by the agent's shell**, so it dies when the turn ends, times out, or the app restarts.
  26. - Or you **come back later** and have to re-explain everything to a fresh conversation.
  27. ## The fix
  28. **Long Task Callback (`ltc`)** hands the job to an independent, OS-native process owner and, when it
  29. finishes, **resumes the exact same conversation** with a compact result — exit code, log path,
  30. artifacts, and the command to acknowledge it.
  31. ```console
  32. $ ltc run --task "train model" -- python train.py --config configs/exp.yaml
  33. ltc: submitted managed task <task-id>
  34. ltc: execution backend: systemd
  35. ...
  36. ```
  37. The agent ends its turn — zero model calls while it waits. Two hours later, the **same session**
  38. receives a short envelope like this:
  39. ```text
  40. [long-task-callback] <callback-id>
  41. Task: train model
  42. Result: finished; exit=0
  43. Files: ~/.ltc/tasks/<task-id>/ (attempt-1.log)
  44. Details: .../details/<callback-id>.md (as needed)
  45. Session: <session-id> (only)
  46. ...plus the exact `ltc ack` command to run
  47. ```
  48. ## ✨ Highlights
  49. | | |
  50. | --- | --- |
  51. | 🛌 **No polling** | The worker and daemon wait for you. No model turns are spent while the task runs. |
  52. | 🔁 **Same conversation** | Callbacks are bound to the original Codex (`CODEX_THREAD_ID`), Claude Code (`CLAUDE_CODE_SESSION_ID`), Pi (`PI_SESSION_FILE`) or DeepSeek Harness (`DSH_SESSION_ID`) session — never a guess. |
  53. | 🧱 **Survives the agent** | Tasks run under systemd, launchd or Task Scheduler — not as a child of the agent turn or even the daemon. |
  54. | ⚡ **Claude Code native** | In Claude Code (CLI or desktop app), a background `ltc wait` wakes the conversation you're looking at — no headless side session. → [Claude Code guide](docs/claude-code.md) |
  55. | 🥧 **Pi native** | Pi's extension steers the result into the running Pi session — even mid-run, before its next model call. → [Pi guide](docs/pi.md) |
  56. | 🧭 **DeepSeek Harness native** | A background `ltc wait` runs as a DSH job; its completion notification wakes the same conversation. DSH has no headless fallback, so delivery is always the original live session. → [DSH guide](docs/dsh.md) |
  57. | 🤖 **Child agents** | `ltc agent codex\|claude\|pi\|dsh` launches a fresh agent as a durable background job, with reusable prompt templates. |
  58. | 🎯 **Multi-stage goals** | Track an objective across many callbacks with a YAML plan that the agent must verify before declaring victory. |
  59. | 🛡️ **Never reruns blindly** | Ambiguous launches, reboots and failures are reported to the agent for inspection — LTC never silently replays work. |
  60. | 🩺 **Self-repairing setup** | When something is misconfigured, the agent gets a machine-readable repair plan and fixes it itself. |
  61. | 📬 **At-least-once delivery** | Durable queue, stable callback IDs, retries with backoff, and explicit ACKs. |
  62. ## 🚀 Quick start
  63. ```bash
  64. # 1. Install (stable release)
  65. python3 -m pip install "git+https://github.com/lz59970062/long-task-wakeup.git@v0.7.0"
  66. # 2. Install the skill for Codex + Claude Code and start the background daemon
  67. ltc setup --force --enable --now
  68. # Using Pi too? Add --with-pi-extension (Pi skill + live-callback extension)
  69. # Using DeepSeek Harness too? Add --with-dsh (skill + launcher discovery)
  70. # 3. Check that everything is healthy
  71. ltc --version
  72. ltc doctor --agent codex --session <session-id>
  73. ```
  74. That's it. `setup` installs the bundled skill, so your agent already knows when and how to use `ltc`.
  75. From inside a Codex, Claude Code or DeepSeek Harness session, just ask it to run something long.
  76. <details>
  77. <summary><b>Platform requirements</b></summary>
  78. | Platform | Task owner | Coordinator | Notes |
  79. | --- | --- | --- | --- |
  80. | **Linux** | Independent systemd user service (v240+) | systemd user service | Falls back to GNU `screen` when no user systemd is available (e.g. Docker, AutoDL). See [containers](docs/containers.md). |
  81. | **macOS** | One-shot launchd job in the GUI session | LaunchAgent | No `screen` needed. See [macOS guide](docs/macos.md). |
  82. | **Windows 10+** | Per-user Task Scheduler task + Job Object | Login scheduled task | Requires a logged-in session and an ACL-capable filesystem (NTFS). See [Windows guide](docs/windows.md). |
  83. The backend is recorded when a task is submitted and is never silently changed during recovery.
  84. To use the screen compatibility backend: `sudo apt install screen` (or `dnf install screen`), then
  85. `ltc run --backend screen ...`.
  86. </details>
  87. <details>
  88. <summary><b>Trying the 0.7.1 preview (Desktop callbacks)</b></summary>
  89. `main` currently carries the **0.7.1 preview**, which adds explicit callback modes
  90. (`cli`, `codex-queue`, `manual`, `auto`). From a Codex Desktop session, `auto` delivers
  91. through the public `codex queue` command, so Desktop needs no launcher or restart.
  92. ```bash
  93. # Installs from main and runs setup with the same interpreter
  94. ./scripts/install_from_git.sh https://github.com/lz59970062/long-task-wakeup.git
  95. # Windows: scripts/install_from_git.ps1 -RepoUrl https://github.com/lz59970062/long-task-wakeup.git
  96. ```
  97. Read [callback modes](docs/callback-modes.md) and [Codex Desktop](docs/integrations/desktop.en.md)
  98. for the states and limits: verified with real Codex on Linux; a real Desktop app, macOS and Windows have not been run.
  99. </details>
  100. ## 🧭 How it works
  101. <p align="center">
  102. <img src="./assets/readme/workflow.svg" width="100%" alt="The agent submits a task, the daemon requests an independent task service, the task runs independently, completion is queued, and the same agent conversation resumes and acknowledges it">
  103. </p>
  104. ```text
  105. systemd user service (Linux) / LaunchAgent (macOS) / login scheduled task (Windows)
  106. └─ ltc daemon control, recovery and callback delivery
  107. Independent per-task service (screen for legacy tasks)
  108. └─ LTC worker
  109. └─ training / benchmark / build / child agent
  110. ```
  111. 1. **Submit** — the agent calls `ltc run` or `ltc agent`. LTC durably records the command, environment,
  112. original session binding, backend and log path, then returns immediately.
  113. 2. **Own** — the daemon asks the OS for a separate task service. The task is *not* a child of the agent or the daemon.
  114. 3. **Run** — the job runs for minutes or hours. Nobody polls.
  115. 4. **Queue** — on exit, LTC stores the result and queues a callback for the original conversation.
  116. 5. **Resume** — the same session wakes up, inspects the result, and runs `ltc ack`.
  117. > **Rule of thumb:** anything reliably done in under 60 seconds can run in the foreground.
  118. > Anything longer — or of uncertain duration — goes through `ltc run`.
  119. ## 📖 Usage
  120. LTC has three entry points:
  121. | Command | Use it when… |
  122. | --- | --- |
  123. | `ltc run -- <command>` | You want LTC to **launch and own** a new long task. |
  124. | `ltc agent codex\|claude\|pi -- <prompt>` | You want a **fresh child agent** to work in the background and report back. |
  125. | `ltc done ...` | The task is **already owned** by screen, tmux, Slurm or another scheduler — just report completion. |
  126. ### `run` — submit a long task
  127. ```bash
  128. ltc run \
  129. --cwd "$PWD" \
  130. --task "train model" \
  131. -- python train.py --config configs/exp.yaml
  132. ```
  133. Returns as soon as the task is durable, printing the task ID, backend and log file:
  134. ```bash
  135. tail -f ~/.ltc/tasks/<task-id>/attempt-1.log
  136. ```
  137. ### DeepSeek Harness: wake the live session
  138. DSH keeps background jobs alive across turns and notifies the conversation when one exits. After
  139. `ltc run`, it prints the exact command to start with `run_in_background: true`:
  140. ```bash
  141. ltc wait --queue-dir ~/.ltc/queue --task <task-id>
  142. ```
  143. Read the finished job's output with `job_output`; that output is the callback. DSH's one-shot
  144. runner refuses desktop-preset sessions, and a second writer would race the live writer lock, so LTC
  145. never resumes a DSH conversation headlessly: with no waiter the callback stays queued until this
  146. session runs `ltc wait` again. → [DSH guide](docs/dsh.md)
  147. ### Claude Code: wake the live session
  148. Claude Code wakes a session when a background shell command exits. After `ltc run`, it prints the
  149. exact command to run with `run_in_background`:
  150. ```bash
  151. ltc wait --queue-dir ~/.ltc/queue --task <task-id>
  152. ```
  153. `ltc wait` exits — and the session wakes up — as soon as the callback is queued. While a waiter is
  154. alive the daemon stays out of the way; if the session is gone, the daemon falls back to a headless
  155. `claude -p --resume` from the session's original directory. The installed Claude skill teaches
  156. Claude to do this on its own. → [Claude Code guide](docs/claude-code.md)
  157. ### `agent` — delegate to a background child agent
  158. ```bash
  159. ltc agent claude --cwd "$PWD" --task "review parser edge cases" \
  160. -- "Inspect parser.py and its tests. Report concrete defects and suggested fixes."
  161. ltc agent codex --template test --task "write parser tests" \
  162. -- "Use docs/parser-contract.md to test parser.py, including invalid input and boundaries."
  163. ```
  164. The child gets its own private prompt/result files; the callback still goes to *your* conversation.
  165. Use `--template` / `--template-file` for reusable prompts, `--model` / `--reasoning-effort` to pin
  166. the child's model, and `--dry-run` to preview. → [Agent mode & templates](docs/agent-mode.md)
  167. ### `done` — report an externally managed task
  168. ```bash
  169. set +e
  170. python train.py --config configs/exp.yaml
  171. status=$?
  172. ltc done --cwd "$PWD" --task "train model" \
  173. --command "python train.py --config configs/exp.yaml" --exit-code "$status"
  174. exit "$status"
  175. ```
  176. Drop this into a screen/tmux session, Slurm epilogue, shell trap or Python `finally`. `done` only
  177. queues the callback — it doesn't make the preceding process durable.
  178. ### Acknowledge, inspect, cancel
  179. ```bash
  180. ltc wait --task <task-id> # (Claude Code) block until the callback is ready, then print it
  181. ltc ack --id <callback-id> # confirm a callback was received and inspected
  182. ltc status # list callbacks that still need handling
  183. ltc cancel --id <callback-id> # cancel a queued callback
  184. ltc retry --id <callback-id> # (0.7.1) re-deliver a result without rerunning the task
  185. ltc doctor --agent codex --session <id> # JSON readiness report + repair plan
  186. ```
  187. ### Multi-stage goals
  188. Callback ACK says *"I saw this result."* Goal ACK says *"the whole objective is done (or blocked)."*
  189. ```bash
  190. ltc goal start --id report-goal --session <session-id> --cwd "$PWD" \
  191. --task "finish the report" --plan-file .ltc/goals/report-goal.yaml
  192. ltc goal check --id report-goal
  193. ltc goal ack --id report-goal --state completed --plan-sha256 <checked-sha256>
  194. ```
  195. The plan is an editable YAML path of steps. Completion is rejected unless every step is `completed`
  196. and the digest matches a fresh `goal check`. Idle goals get a status nudge every three hours.
  197. → [Goals guide](docs/goals.md)
  198. ### Session binding
  199. Inside an agent conversation, LTC binds automatically via `CODEX_THREAD_ID` (Codex) or
  200. `CLAUDE_CODE_SESSION_ID` (Claude Code). You can also bind explicitly:
  201. ```bash
  202. ltc done --agent claude --session <session-id> --cwd "$PWD" --task "external job" --exit-code 0
  203. ```
  204. If no target can be determined, LTC fails instead of guessing. (`--last` exists but always warns.)
  205. ## 🔒 Guarantees and boundaries
  206. - **At-least-once delivery.** Unacknowledged callbacks retry with backoff. After a host failure a callback
  207. may arrive twice, so resumed agents inspect existing processes and artifacts before acting.
  208. - **No blind reruns.** After a reboot, LTC wakes the original session with the task, log path and
  209. interruption reason — the agent decides whether to resume from a checkpoint. There is no `--resume-command`.
  210. - **No cross-host recovery.** LTC does not move workspaces, data, checkpoints or credentials between machines.
  211. - **Private state.** Everything lives under `${LTC_HOME:-~/.ltc}/`; full callback
  212. details are saved privately in `details/<callback-id>.md`. An older
  213. `~/.codex/long-task-wakeup/` is moved there on first run and left as a symlink.
  214. More in [recovery & self-repair](docs/recovery.md) and [architecture](docs/architecture.md).
  215. <details>
  216. <summary><b>Upgrading from 0.6</b></summary>
  217. Drain existing work and upgrade the coordinator before submitting native tasks, or use a separate 0.7
  218. queue and Agent profile — the 0.6 daemon does not understand native task records. Pass the same
  219. `--queue-dir /absolute/path/to/ltc-queue` to `ltc daemon`, `ltc run` and `ltc ack`. Standalone
  220. coordinators also need separate `CODEX_HOME` profiles. The submitting shell must carry the original
  221. Agent session ID (or pass `--session`). Old scripts may still pass `--via-daemon`; it is a hidden no-op.
  222. </details>
  223. <details>
  224. <summary><b>Service management</b></summary>
  225. ```bash
  226. # Linux
  227. systemctl --user status codex-long-task-wakeup.service
  228. journalctl --user -u codex-long-task-wakeup.service -f
  229. # macOS
  230. launchctl print "gui/$(id -u)/codex-long-task-wakeup"
  231. ```
  232. `ltc setup --service auto` picks systemd (Linux), launchd (macOS) or `windows-task` (Windows).
  233. Use `--service standalone --now` where user systemd is unavailable (e.g. AutoDL), or
  234. `--service supervisor` explicitly. Standalone setup does not register startup on its own — see
  235. [containers](docs/containers.md) for boot hooks, Supervisor and Docker restart policies.
  236. </details>
  237. ## 📚 Documentation
  238. [中文文档站](https://lz59970062.github.io/long-task-wakeup/) · [文档源码](docs/index.md)
  239. | Topic | |
  240. | --- | --- |
  241. | Claude Code: live callbacks, binary discovery, session directories | [docs/claude-code.md](docs/claude-code.md) |
  242. | Pi: steered live callbacks, managed sessions, Pi child agents | [docs/pi.md](docs/pi.md) |
  243. | DeepSeek Harness: live jobs, no headless resume, DSH child agents | [docs/dsh.md](docs/dsh.md) |
  244. | Agent mode, templates, Claude Code config | [docs/agent-mode.md](docs/agent-mode.md) |
  245. | Registering templates as discoverable skills | [docs/template-registration.md](docs/template-registration.md) |
  246. | Goals and acknowledgement layers | [docs/goals.md](docs/goals.md) |
  247. | Callback format, reminder cadence, user hook | [docs/callback-reminders.md](docs/callback-reminders.md) |
  248. | Callback modes (CLI / Codex queue / manual) — 0.7.1 | [docs/callback-modes.md](docs/callback-modes.md) |
  249. | Restart, recovery and self-repair | [docs/recovery.md](docs/recovery.md) |
  250. | Architecture and extension points | [docs/architecture.md](docs/architecture.md) |
  251. | macOS · Windows · Containers | [macOS](docs/macos.md) · [Windows](docs/windows.md) · [Containers](docs/containers.md) |
  252. | Codex Desktop | [Guide](docs/integrations/desktop.en.md) |
  253. | Validation records | [0.7.0](docs/validation-0.7.0.md) · [0.7.1 preview](docs/validation-0.7.1-preview.md) · [Linux preview](docs/validation-0.7.0a1.md) · [macOS](docs/validation-macos.md) · [Windows](docs/validation-windows.md) |
  254. | Release history | [CHANGELOG.md](CHANGELOG.md) |
  255. ## 🗺️ Roadmap
  256. - [x] Native task owners on Linux, macOS and Windows (0.7.0)
  257. - [x] Fresh child agents with templates (0.6.5)
  258. - [ ] Explicit callback modes and native Codex queue delivery (0.7.1 preview)
  259. - [ ] Claude Code live callbacks via `ltc wait` (0.7.1 preview; verified on macOS and Linux)
  260. - [ ] Pi agent adapter: child worker and steered live callbacks (0.7.1 preview; verified on Linux)
  261. - [ ] DeepSeek Harness adapter: child worker and live `ltc wait` callbacks (0.7.1 preview)
  262. ## License
  263. [MIT](LICENSE) · Formerly `codex-long-task-wakeup` — the old command remains an alias for `ltc`.
src/long_task_callback/template_registration.py · Bundled script · 516 lines · 1 finding marked
  1. """Publish named templates and small discoverable skills from one registration.
  2. The registry owns generated entrypoints, not the user's main LTC instructions.
  3. Only a delimited index in those instructions is refreshed. Task execution still
  4. uses the existing template loader and durable child-agent lifecycle.
  5. """
  6. from __future__ import annotations
  7. import contextlib
  8. import hashlib
  9. import importlib.resources as resources
  10. import json
  11. import os
  12. from pathlib import Path
  13. import re
  14. import shlex
  15. from dataclasses import dataclass, field
  16. import yaml
  17. from . import storage
  18. from .agents import get_child_agent
  19. from .platforms import posix, windows_io
  20. from .templates import _UniqueSafeLoader, load_template, user_template_dir
  21. INDEX_BEGIN = "<!-- ltc:registered-templates:begin -->"
  22. INDEX_END = "<!-- ltc:registered-templates:end -->"
  23. REGISTRY_NAME = ".ltc-registrations.json"
  24. def _digest(text: str) -> str:
  25. return hashlib.sha256(text.encode("utf-8")).hexdigest()
  26. def _read(path: Path) -> str | None:
  27. if path.is_symlink():
  28. raise ValueError(f"refusing to replace a symlink: {path}")
  29. try:
  30. with path.open(encoding="utf-8", newline="") as handle:
  31. return handle.read()
  32. except FileNotFoundError:
  33. return None
  34. def _registry() -> dict:
  35. path = user_template_dir() / REGISTRY_NAME
  36. text = _read(path)
  37. if text is None:
  38. return {"version": 1, "templates": {}}
  39. try:
  40. data = json.loads(text)
  41. if data.get("version") != 1 or not isinstance(data.get("templates"), dict):
  42. raise ValueError("unsupported registration registry")
  43. for name, entry in data["templates"].items():
  44. _name(name)
  45. if (not isinstance(entry, dict)
  46. or not isinstance(entry.get("skill_roots"), list)
  47. or not all(isinstance(p, str) and Path(p).is_absolute() for p in entry["skill_roots"])
  48. or not isinstance(entry.get("files"), dict)
  49. or not isinstance(entry.get("aliases"), dict)
  50. or not isinstance(entry.get("parent_homes"), dict)
  51. or not isinstance(entry.get("description"), str)):
  52. raise ValueError(f"invalid registration for {name}")
  53. get_child_agent(entry.get("worker"))
  54. return data
  55. except (ValueError, AttributeError) as exc:
  56. raise ValueError(f"cannot read registration registry {path}: {exc}") from exc
  57. def _name(name: str) -> None:
  58. if (not isinstance(name, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,58}", name)
  59. or name.endswith("-") or "--" in name):
  60. raise ValueError("registered template names must use lowercase letters, digits and hyphens (up to 59 characters)")
  61. def _roots(target: str) -> tuple[list[Path], list[tuple[Path, Path]]]:
  62. roots = []
  63. aliases = []
  64. if target in ("codex", "both"):
  65. home = Path(os.environ.get("CODEX_HOME", "~/.codex")).expanduser().resolve()
  66. default = home == (Path.home() / ".codex").resolve()
  67. root = home / "skills"
  68. if default and os.name == "nt":
  69. root = Path.home() / ".agents" / "skills"
  70. roots.append(root)
  71. if default and os.name != "nt":
  72. aliases.append((Path.home() / ".agents" / "skills", root))
  73. if target in ("claude", "both"):
  74. roots.append(Path(os.environ.get("CLAUDE_CONFIG_DIR", "~/.claude")).expanduser().resolve() / "skills")
  75. return roots, aliases
  76. def _namespace_markers() -> tuple[str, str]:
  77. namespace = _digest(str(user_template_dir().resolve()))
  78. prefix = f"<!-- ltc:registered-templates:namespace:{namespace}"
  79. return f"{prefix}:begin -->", f"{prefix}:end -->"
  80. def _index_range(text: str) -> tuple[int, int] | None:
  81. if INDEX_BEGIN not in text and INDEX_END not in text:
  82. return None
  83. if text.count(INDEX_BEGIN) != 1 or text.count(INDEX_END) != 1:
  84. raise ValueError("LTC registered-template index markers are damaged; preserve and repair them before registration")
  85. start, end = text.index(INDEX_BEGIN), text.index(INDEX_END)
  86. if end < start:
  87. raise ValueError("LTC registered-template index markers are reversed")
  88. return start + len(INDEX_BEGIN), end
  89. def _index(text: str, entries: dict, root: Path) -> str:
  90. canonical_root = root.resolve()
  91. selected = [(name, entry) for name, entry in sorted(entries.items())
  92. if any(Path(path).resolve() == canonical_root for path in entry.get("skill_roots", []))]
  93. namespace_begin, namespace_end = _namespace_markers()
  94. lines = [namespace_begin]
  95. for name, entry in selected:
  96. lines.append(f"- `{name}`: {entry['description']} Read [ltc-{name}](../ltc-{name}/SKILL.md) to delegate to {entry['worker']}.")
  97. lines.append(namespace_end)
  98. namespace_block = "\n".join(lines) if selected else ""
  99. index_range = _index_range(text)
  100. if index_range is not None:
  101. content_start, end = index_range
  102. content = text[content_start:end]
  103. if namespace_begin in content or namespace_end in content:
  104. if content.count(namespace_begin) != 1 or content.count(namespace_end) != 1:
  105. raise ValueError("LTC registration namespace markers are damaged; preserve and repair them before registration")
  106. namespace_start = content.index(namespace_begin)
  107. namespace_finish = content.index(namespace_end)
  108. if namespace_finish < namespace_start:
  109. raise ValueError("LTC registration namespace markers are reversed")
  110. content = (content[:namespace_start] + namespace_block
  111. + content[namespace_finish + len(namespace_end):])
  112. elif namespace_block:
  113. # Retain other namespaces and any older unlabelled index content.
  114. content += ("" if content.endswith("\n") else "\n") + namespace_block + "\n"
  115. return text[:content_start] + content + text[end:]
  116. if not selected:
  117. return text
  118. block = f"{INDEX_BEGIN}\n{namespace_block}\n{INDEX_END}"
  119. return text + ("\n" if text.endswith("\n") else "\n\n") + "## Registered task templates\n\n" + block + "\n"
  120. def _skill(name: str, entry: dict, root: Path) -> str:
  121. metadata = yaml.safe_dump({"name": f"ltc-{name}", "description": entry["description"]},
  122. sort_keys=False, allow_unicode=True).rstrip()
  123. template = shlex.quote(entry["template_file"])
  124. return (f"---\n{metadata}\n---\n\n"
  125. f"<!-- ltc:template-entry:{name} -->\n"
  126. f"<!-- ltc:template-owner:{_digest(str(user_template_dir().resolve()))} -->\n"
  127. f"# {name}\n\n"
  128. f"Delegate this task to a fresh {entry['worker']} child using the registered LTC template.\n"
  129. f"Read [the LTC workflow]({root / 'long-task-callback' / 'SKILL.md'}) before submission\n"
  130. "for readiness checks, parent-session callbacks and acknowledgement.\n\n"
  131. "Pass the user's actual requirements, scope, target paths and evidence constraints.\n"
  132. "Distinguish review-only requests from authorized file edits.\n\n"
  133. "```bash\n"
  134. f"ltc agent {entry['worker']} --template-file {template} --cwd /absolute/path/to/workspace "
  135. ' -- "The user\'s concrete task requirements."\n'
  136. "```\n\n"
  137. f"Installed template: `{entry['template_file']}`. This file selects the registered\n"
  138. "configuration even when another workspace sets a different LTC_TEMPLATE_DIR.\n"
  139. "Inspect the actual result and edits, ACK the callback, and continue the parent task.\n")
  140. @dataclass
  141. class _Plan:
  142. writes: dict[Path, str | None] = field(default_factory=dict)
  143. before: dict[Path, str | None] = field(default_factory=dict)
  144. resolved: dict[Path, Path] = field(default_factory=dict)
  145. links: dict[Path, Path] = field(default_factory=dict)
  146. unlink: list[Path] = field(default_factory=list)
  147. def write(self, path: Path, text: str | None) -> None:
  148. path = path.absolute()
  149. self.before[path] = _read(path)
  150. self.resolved[path] = path.resolve()
  151. if self.before[path] != text:
  152. self.writes[path] = text
  153. def link(self, path: Path, destination: Path) -> None:
  154. if path.is_symlink():
  155. if path.resolve() != destination.resolve():
  156. raise ValueError(f"preserving an unrelated skill alias: {path}")
  157. elif path.exists():
  158. raise ValueError(f"preserving an existing skill directory: {path}")
  159. else:
  160. self.links[path] = destination
  161. def apply(self) -> None:
  162. completed = []
  163. linked = []
  164. removed = []
  165. try:
  166. for path, original in self.before.items():
  167. if path.resolve() != self.resolved[path] or _read(path) != original:
  168. raise ValueError(f"file changed during registration: {path}")
  169. ordered = [(p, text) for p, text in self.writes.items() if p.name != REGISTRY_NAME]
  170. for path, text in ordered:
  171. # Record before publication: a directory fsync can fail after replace.
  172. completed.append(path)
  173. if text is None:
  174. path.unlink(missing_ok=True)
  175. else:
  176. storage.write_private_text(path, text, preserve_newlines=True)
  177. for path, destination in self.links.items():
  178. path.parent.mkdir(parents=True, exist_ok=True)
  179. path.symlink_to(destination, target_is_directory=True)
  180. linked.append(path)
  181. for path in self.unlink:
  182. destination = Path(os.readlink(path))
  183. path.unlink()
  184. removed.append((path, destination))
  185. for path, text in self.writes.items():
  186. if path.name == REGISTRY_NAME:
  187. completed.append(path)
  188. storage.write_private_text(path, text, preserve_newlines=True)
  189. except BaseException as exc:
  190. failures = []
  191. for path, destination in reversed(removed):
  192. try:
  193. path.symlink_to(destination, target_is_directory=True)
  194. except OSError:
  195. failures.append(str(path))
  196. for path in reversed(linked):
  197. try:
  198. path.unlink()
  199. except OSError:
  200. failures.append(str(path))
  201. for path in reversed(completed):
  202. original = self.before[path]
  203. try:
  204. if original is None:
  205. path.unlink(missing_ok=True)
  206. else:
  207. storage.write_private_text(path, original, preserve_newlines=True)
  208. except OSError:
  209. failures.append(str(path))
  210. if failures:
  211. raise RuntimeError(f"registration failed ({exc}); could not restore: {', '.join(failures)}") from exc
  212. raise
  213. def summary(self) -> dict:
  214. return {"write": [str(path) for path, value in self.writes.items() if value is not None],
  215. "remove": [str(path) for path, value in self.writes.items() if value is None] + [str(p) for p in self.unlink],
  216. "aliases": {str(path): str(destination) for path, destination in self.links.items()}}
  217. def _owned_write(plan: _Plan, path: Path, text: str, old: dict, *, force: bool) -> None:
  218. current = _read(path)
  219. previous = old.get("files", {}).get(str(path))
  220. if current is not None and current != text and _digest(current) != previous and not force:
  221. raise ValueError(f"preserving an existing or edited file: {path}; use --force to replace it")
  222. plan.write(path, text)
  223. def _refresh_indexes(plan: _Plan, entries: dict, roots: list[Path], *, install_missing: bool = False) -> None:
  224. for root in sorted(set(roots)):
  225. path = (root / "long-task-callback" / "SKILL.md").resolve()
  226. text = _read(path)
  227. if text is None and install_missing:
  228. package = resources.files("long_task_callback").joinpath("skill")
  229. text = package.joinpath("SKILL.md").read_text(encoding="utf-8")
  230. if any(entry.get("parent_homes", {}).get("codex") == str(root) for entry in entries.values()):
  231. metadata = path.parent / "agents" / "openai.yaml"
  232. if _read(metadata) is None:
  233. plan.write(metadata, package.joinpath("agents").joinpath("openai.yaml").read_text(encoding="utf-8"))
  234. if text is not None:
  235. plan.write(path, _index(text, entries, root))
  236. def _save_registry(plan: _Plan, data: dict) -> None:
  237. # This publication is last, after every entrypoint and dependency is valid.
  238. plan.write(user_template_dir() / REGISTRY_NAME, json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
  239. def _register_plan(args) -> tuple[_Plan, dict]:
  240. _name(args.name)
  241. source = load_template(template_file=args.file) if args.file else load_template(args.name)
  242. if source.source.startswith("builtin:"):
  243. raise ValueError("registration requires a user YAML template; use --file to supply one")
  244. worker = args.worker or source.worker
  245. if worker is None:
  246. raise ValueError("registration requires worker in the YAML or --worker")
  247. get_child_agent(worker)
  248. description = args.description or source.description
  249. if not isinstance(description, str) or not description.strip():
  250. raise ValueError("registration requires description in the YAML or --description")
  251. description = " ".join(description.split())
  252. if len(description) > 1024:
  253. raise ValueError("registration description must be at most 1024 characters")
  254. if "<!-- ltc:" in description:
    • Note: Quoted as data in code: Gives the agent orders in an HTML comment, which the rendered page hides from a reader
    • Line 292 on GitHub
  255. raise ValueError("registration description cannot contain reserved LTC index markers")
  256. data = _registry()
  257. old = data["templates"].get(args.name, {})
  258. roots, alias_roots = _roots(args.target)
  259. parents = (["codex", "claude"] if args.target == "both" else [args.target])
  260. parent_homes = dict(old.get("parent_homes", {}))
  261. for parent, root in zip(parents, roots):
  262. previous = parent_homes.get(parent)
  263. if previous is not None and previous != str(root):
  264. raise ValueError(f"{args.name} is already registered in another {parent} home; use its original profile or a separate LTC_TEMPLATE_DIR")
  265. parent_homes[parent] = str(root)
  266. # Existing targets are retained when updating a registration.
  267. roots = list(dict.fromkeys([*map(Path, old.get("skill_roots", [])), *roots]))
  268. for root in roots:
  269. previous = old.get("root_identities", {}).get(str(root))
  270. if previous is not None and previous != str(root.resolve()):
  271. raise ValueError(f"preserving a changed skill directory: {root}")
  272. directory = user_template_dir()
  273. if (directory / f"{args.name}.yml").exists() or (directory / f"{args.name}.yml").is_symlink():
  274. raise ValueError(f"preserving existing {args.name}.yml; move it before registering a .yaml template")
  275. template_path = directory / f"{args.name}.yaml"
  276. raw = yaml.load(Path(source.source).read_text(encoding="utf-8"), Loader=_UniqueSafeLoader)
  277. raw["worker"], raw["description"] = worker, description
  278. files = {}
  279. for agent, settings in source.agent_defaults.items():
  280. if "system_prompt_file" not in settings:
  281. continue
  282. path = source.system_prompt_file_for(agent)
  283. if not path.is_file():
  284. raise ValueError(f"system prompt must be a readable regular file: {path}")
  285. with path.open(encoding="utf-8-sig", newline="") as handle:
  286. text = handle.read()
  287. if not text.strip() or "\x00" in text:
  288. raise ValueError(f"system prompt must contain non-empty UTF-8 text: {path}")
  289. asset_root = directory / ".ltc-assets"
  290. if asset_root.is_symlink() or (asset_root / args.name).is_symlink():
  291. raise ValueError(f"preserving an existing template asset symlink: {asset_root / args.name}")
  292. destination = asset_root / args.name / f"system-prompt-{agent}.md"
  293. files[destination] = text
  294. raw[agent]["system_prompt_file"] = destination.relative_to(directory).as_posix()
  295. files[template_path] = yaml.safe_dump(raw, sort_keys=False, allow_unicode=True)
  296. entry = {"worker": worker, "description": description, "version": source.version,
  297. "template_file": str(template_path), "source": old.get("source", source.source) if source.source == str(template_path) else source.source,
  298. "skill_roots": [str(root) for root in roots], "files": {},
  299. "parent_homes": parent_homes,
  300. "root_identities": {str(root): str(root.resolve()) for root in roots},
  301. "aliases": dict(old.get("aliases", {}))}
  302. plan = _Plan()
  303. for root in roots:
  304. skill_path = root / f"ltc-{args.name}" / "SKILL.md"
  305. parent = skill_path.parent
  306. # A registration cannot claim an unrelated skill, even with --force.
  307. if parent.is_symlink():
  308. raise ValueError(f"preserving an existing skill symlink: {parent}")
  309. current = _read(skill_path)
  310. owner = f"<!-- ltc:template-owner:{_digest(str(directory.resolve()))} -->"
  311. if current is not None and (f"<!-- ltc:template-entry:{args.name} -->" not in current or owner not in current):
  312. raise ValueError(f"preserving an unrelated skill: {skill_path}")
  313. if parent.exists() and current is None and any(parent.iterdir()):
  314. raise ValueError(f"preserving an existing skill directory: {parent}")
  315. files[skill_path] = _skill(args.name, entry, root)
  316. if str(root) == parent_homes.get("codex"):
  317. if (parent / "agents").is_symlink():
  318. raise ValueError(f"preserving an existing metadata symlink: {parent / 'agents'}")
  319. interface = {"display_name": f"{args.name.replace('-', ' ').title()} ({worker.title()})",
  320. "short_description": f"Delegate {args.name[:30]} to {worker} with LTC",
  321. "default_prompt": f"Use $ltc-{args.name} to delegate this task to the registered {worker} child agent."}
  322. files[parent / "agents" / "openai.yaml"] = yaml.safe_dump({"interface": interface}, sort_keys=False, allow_unicode=True)
  323. for path, text in files.items():
  324. _owned_write(plan, path, text, old, force=args.force)
  325. entry["files"][str(path)] = _digest(text)
  326. for alias_root, root in alias_roots:
  327. alias, destination = alias_root / f"ltc-{args.name}", root / f"ltc-{args.name}"
  328. plan.link(alias, destination)
  329. entry["aliases"][str(alias)] = str(destination)
  330. data["templates"][args.name] = entry
  331. _refresh_indexes(plan, data["templates"], roots, install_missing=True)
  332. _save_registry(plan, data)
  333. return plan, entry
  334. def _unregister_plan(name: str) -> tuple[_Plan, dict | None]:
  335. _name(name)
  336. data = _registry()
  337. entry = data["templates"].get(name)
  338. plan = _Plan()
  339. if entry is None:
  340. return plan, None
  341. roots = list(map(Path, entry["skill_roots"]))
  342. for root in roots:
  343. previous = entry.get("root_identities", {}).get(str(root))
  344. if previous is not None and previous != str(root.resolve()):
  345. raise ValueError(f"preserving a changed skill directory: {root}")
  346. path = root / f"ltc-{name}" / "SKILL.md"
  347. if path.parent.is_symlink():
  348. raise ValueError(f"preserving a changed entrypoint directory: {path.parent}")
  349. current = _read(path)
  350. if current is not None and _digest(current) != entry["files"].get(str(path)):
  351. raise ValueError(f"preserving edited entrypoint: {path}; restore it before unregistering")
  352. plan.write(path, None)
  353. metadata = path.parent / "agents" / "openai.yaml"
  354. if str(metadata) in entry["files"]:
  355. if metadata.parent.is_symlink():
  356. raise ValueError(f"preserving a changed metadata directory: {metadata.parent}")
  357. current = _read(metadata)
  358. if current is not None and _digest(current) != entry["files"][str(metadata)]:
  359. raise ValueError(f"preserving edited entrypoint metadata: {metadata}; restore it before unregistering")
  360. plan.write(metadata, None)
  361. for path_text, destination in entry.get("aliases", {}).items():
  362. path = Path(path_text)
  363. if path.is_symlink() and path.resolve() == Path(destination).resolve():
  364. plan.unlink.append(path)
  365. elif path.exists() or path.is_symlink():
  366. raise ValueError(f"preserving changed skill alias: {path}")
  367. del data["templates"][name]
  368. _refresh_indexes(plan, data["templates"], roots)
  369. _save_registry(plan, data)
  370. return plan, entry
  371. def _lock_paths(roots) -> list[Path]:
  372. paths = {user_template_dir().resolve() / ".ltc-registration.lock"}
  373. for root in roots:
  374. root = Path(root).resolve()
  375. paths.add(root / ".ltc-registration.lock")
  376. # A main workflow directory may itself link to another shared skill root.
  377. workflow_root = (root / "long-task-callback" / "SKILL.md").resolve().parent.parent
  378. paths.add(workflow_root / ".ltc-registration.lock")
  379. return sorted(paths, key=str)
  380. @contextlib.contextmanager
  381. def _lock(roots=()):
  382. platform = windows_io if os.name == "nt" else posix
  383. leases = []
  384. paths = _lock_paths(roots)
  385. try:
  386. for path in paths:
  387. if path.is_symlink():
  388. raise ValueError(f"preserving an existing registration lock symlink: {path}")
  389. lease = platform.acquire_path_lock(path, blocking=False)
  390. if lease is None:
  391. raise ValueError("another template registration is running; retry after it completes")
  392. leases.append(lease)
  393. yield frozenset(paths)
  394. finally:
  395. for lease in reversed(leases):
  396. lease[0].close()
  397. def _require_locked_roots(roots, locked_paths) -> None:
  398. if not set(_lock_paths(roots)).issubset(locked_paths):
  399. raise ValueError("registered parent homes changed during registration; retry with the current profile")
  400. def register(args) -> dict:
  401. # Validate the whole plan before creating even the lock file.
  402. plan, entry = _register_plan(args)
  403. if not args.dry_run:
  404. with _lock(entry["skill_roots"]) as locked_paths:
  405. plan, entry = _register_plan(args)
  406. _require_locked_roots(entry["skill_roots"], locked_paths)
  407. plan.apply()
  408. return {"name": args.name, "skill": f"ltc-{args.name}", "worker": entry["worker"],
  409. "template_file": entry["template_file"], "dry_run": args.dry_run,
  410. "changes": plan.summary()}
  411. def unregister(args) -> dict:
  412. plan, entry = _unregister_plan(args.name)
  413. if entry is not None and not args.dry_run:
  414. with _lock(entry["skill_roots"]) as locked_paths:
  415. plan, entry = _unregister_plan(args.name)
  416. if entry is not None:
  417. _require_locked_roots(entry["skill_roots"], locked_paths)
  418. plan.apply()
  419. return {"name": args.name, "registered": False, "dry_run": args.dry_run,
  420. "template_files_preserved": True, "changes": plan.summary()}
  421. def list_templates() -> list[dict]:
  422. return [{"name": name, "skill": f"ltc-{name}", **entry}
  423. for name, entry in sorted(_registry()["templates"].items())]
  424. @contextlib.contextmanager
  425. def preserve_installed_index(target: Path):
  426. """Hold shared locks across installation and retain every registry's index."""
  427. root = target.parent.resolve()
  428. with _lock([root]) as locked_paths:
  429. # Reject unreadable state before the caller replaces the installed tree.
  430. entries = _registry()["templates"]
  431. skill_path = target / "SKILL.md"
  432. previous = _read(skill_path)
  433. previous_range = _index_range(previous) if previous is not None else None
  434. preserved = previous[slice(*previous_range)] if previous_range is not None else None
  435. if previous is not None:
  436. _index(previous, entries, root)
  437. yield
  438. _require_locked_roots([root], locked_paths)
  439. text = _read(skill_path)
  440. if text is None:
  441. raise ValueError(f"installed skill is missing: {skill_path}")
  442. if preserved is not None:
  443. current_range = _index_range(text)
  444. if current_range is not None:
  445. start, end = current_range
  446. text = text[:start] + preserved + text[end:]
  447. else:
  448. text += (("\n" if text.endswith("\n") else "\n\n")
  449. + "## Registered task templates\n\n"
  450. + INDEX_BEGIN + preserved + INDEX_END + "\n")
  451. entries = _registry()["templates"]
  452. updated = _index(text, entries, root)
  453. if updated != _read(skill_path):
  454. storage.write_private_text(skill_path, updated, preserve_newlines=True)
  455. def refresh_installed_skill(target: Path) -> None:
  456. """Reapply the current registry's index without changing other namespaces."""
  457. if not _registry()["templates"]:
  458. return
  459. with preserve_installed_index(target):
  460. pass

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.