bbggkkk

fin-cli AI Agent Specification and Guide

- For full operational steps, read [docs/hermes-agent.md](docs/hermes-agent.md).

bbggkkk 0 Updated 6d ago

Resources

12
GitHub

Install

npx skillscat add bbggkkk/finance-cli

Install via the SkillsCat registry.

SKILL.md

fin-cli AI Agent Specification and Guide

This document provides guidelines for AI agents to interact with the fin-cli tool for broker interaction.

🛠️ Auto-generated Command Documentation

Click on the links below to view the detailed commands and flag schemas for each CLI command category:

💡 AI Agent Execution Rules

  1. AI Output Mode:

    • Always append the --ai flag at the end of your command when programmatic JSON output is needed.
    • Example: ./fin-cli status --ai
    • Start by running fin-cli capabilities --ai to discover the active adapter command schema, safety rules, stable error codes, monitor condition types, condition flags/test inputs, event evaluation reasons, diagnostic recommended-action fields, hook defaults, and local audit paths.
    • When an AI command exits non-zero, parse the JSON error object instead of scraping text. Check capabilities --ai ai.errorCategories, ai.errorCodes, and ai.errorPolicies, then inspect error.category, error.code, error.retryable, error.requiresUserInput, and error.command; validation/auth/permission errors usually need corrected input or user action, network errors can be retried intentionally, and integrity_check_failed means release asset checksums or SHA256SUMS metadata failed verification and should not be retried blindly.
    • Use each capability command's mutates, requiresAuth, liveOrder, and internal fields to decide whether the user must explicitly approve the action before execution.
    • Group/help-style commands such as status, monitor, monitor event, and monitor hook are local metadata commands in capabilities; use subcommand metadata for concrete broker or filesystem effects.
    • Use fin-cli doctor --ai first when diagnosing install, plugin, SKILL, session, monitor, event, or hook state.
    • Check doctor --ai monitor.readiness.ready before long-running monitoring. If it is false, resolve each blockers id before starting or trusting the daemon. If monitor.events.runnable is 0 or blockers include no-runnable-monitor-events, inspect active events for future startsAt, expired definitions, or exhausted repeat alerts before expecting hook delivery.
    • Use capabilities --ai monitor.daemonControl as the source of truth for monitor daemon start/stop/restart/status commands and result fields. A stale status must match monitor.daemonControl.staleStatus before treating it as a restartable crashed daemon.
    • Check doctor --ai plugin path, sourcePath, sha256, version, and versionMatchesCLI fields before trusting a locally installed or loaded plugin.
    • Check doctor --ai operationalLogs before long-running automation; use capabilities --ai ai.diagnosticOperationalLogFields and ai.maintenancePruneResultFields as the parsing contract. If recommendedActions includes prune-operational-logs, run its dry-run command or fin-cli doctor repair --action prune-operational-logs --dry-run=true --ai and review counts before applying with --dry-run=false --confirm=true.
    • Check fin-cli monitor status --ai or doctor --ai monitor.daemonStatus; if it is stale, the recorded daemon PID is not alive. Verify broker auth, run the readiness blocker action's dryRunCommand (fin-cli monitor status --ai) to recheck state, then run fin-cli monitor restart --ai when recommendedActions includes restart-stale-monitor-daemon.
    • If doctor --ai reports active monitor events while the daemon is stopped, run the readiness blocker action's dryRunCommand (fin-cli monitor status --ai) to confirm it is still stopped, then run fin-cli monitor start --ai when recommendedActions includes start-monitor-daemon.
    • fin-cli monitor stop --ai is a local daemon-control command and does not require broker token validation; use it to stop a runaway or stale local daemon even when broker auth is broken.
    • Check doctor --ai monitor.events.expired; if recommendedActions includes review-expired-monitor-events, run its command and decide whether to update, pause, or remove stale alerts.
    • Check doctor --ai monitor.events.exhausted; if recommendedActions includes review-exhausted-monitor-events, run its list command and decide whether to remove, reset with monitor event update --id <event-id> --reset-trigger-count=true --reset-observed-state=true --ai, or recreate completed repeat alerts.
    • Check doctor --ai monitor.hook.failedEntries, retryableFailedEntries, latestFailedDeliveryId, and latestRetryableFailedDeliveryId; if recommendedActions includes replay-failed-monitor-hook, run its dry-run command and review the selected delivery before choosing a safe followUpCommands entry such as applying the latest failed replay, inspecting failed history, previewing retryable failures, or previewing a filtered batch.
    • Check doctor --ai monitor.hook.failedAuditEntries; if recommendedActions includes review-failed-monitor-hook-lifecycle, run fin-cli monitor hook audit --status failed --limit 20 --ai and inspect the sanitized lifecycle failures before retrying registration or removal.
    • Check doctor --ai monitor.hook.secretConfigured; if webhook mode has a URL but no secret and recommendedActions includes repair-monitor-hook-secret, re-register with fin-cli monitor hook register instead of manually editing the hook file.
    • If doctor --ai reports the hook as not configured after a local hook-file edit or migration, treat the persisted hook file as unusable and re-register with monitor hook register; do not hand-edit event_hook.json.
    • The CLI loads bundled/source plugins and the configured global plugin directory; it must not trust a plugins/ directory from the current working directory.
    • Prefer doctor --ai recommendedActions when choosing a repair command; entries include mutates, requiresAuth, requiresUserInput, dryRunCommand, applyCommand, applyRequiresConfirm, and followUpCommands. Run dryRunCommand first when present, and for mutating follow-up commands run their dryRunCommand before command unless the follow-up is explicitly read-only.
    • Use capabilities --ai ai.diagnosticRepairActions to identify which doctor --ai recommendations can be handled by fin-cli doctor repair without user-provided values.
    • For safe no-input repairs, preview fin-cli doctor repair --dry-run=true --ai; apply only with fin-cli doctor repair --dry-run=false --confirm=true --ai after reviewing planned actions. Check capabilities --ai ai.diagnosticRepairResultFields, ai.diagnosticRepairActionResultFields, and ai.diagnosticRepairEffectFields before automating repair result parsing. Repair dry-runs return structured output.effects fields and target paths, with mutation booleans set to false.
    • If doctor --ai reports missing, drifted, or version-mismatched SKILL assets, inspect each skill target's missingDocs, referenceMatchesDoc, and fingerprint fields, then run fin-cli doctor repair --action repair-ai-skill --dry-run=true --ai or fin-cli skill install --dry-run=true --ai before applying fin-cli skill install --ai to reinstall the current release's SKILL and VERSION metadata into Codex and Hermes skill directories. Check capabilities --ai ai.diagnosticSkillFields, ai.skillInstallTargets, ai.skillInstallCommandFields, ai.skillInstallResultFields, and ai.skillInstallEffectFields before automating this flow. In AI mode, each install result includes a stable target value (codex or hermes), concrete path, requested version, doc/reference counts, installedVersion, versionMatchesRequested, and SHA-256 fingerprints (skillSha256, docsSha256, referenceSha256, bundleSha256). Top-level effects distinguishes dry-run (downloadsSkillAssets: "none", mutatesLocalSkillFiles: false) from apply.
    • When installing or repairing a broker plugin directly, use fin-cli plugin install kis --version vX.Y.Z --ai and verify status, pluginName, version, assetName, path, sha256, checksumVerified, effects, and captured installer messages. Check capabilities --ai ai.pluginInstallResultFields and ai.pluginInstallEffectFields before automating this flow; plugin install should report effects.downloadsPluginAssets: "release-assets" and effects.mutatesLocalPluginFiles: true after a successful apply.
    • Use fin-cli upgrade --version vX.Y.Z --ai when the user needs a reproducible pinned CLI/SKILL/plugin version instead of the latest release; installed plugins are refreshed from the same pinned release tag. In AI mode, stdout is JSON and includes status, requestedVersion, targetVersion, currentVersion, developmentMode, binaryUpdated, binaryInstall, skillInstallResults, corePluginsUpdated, installedPluginsAutoUpgradeAttempted, effects, and captured installer messages. Check capabilities --ai ai.upgradeResultFields and ai.upgradeEffectFields; verify binaryInstall.status, path, assetName, sha256, and checksumVerified when binaryUpdated: true, and use effects.mutatesBinary, effects.mutatesSkills, and effects.mutatesPlugins as the top-level mutation summary.
    • Before applying the shell installer on a host, use capabilities --ai ai.installerDryRunTemplate, installerDryRunResultFields, and installerDryRunEffectFields as the contract, then preview with install.sh --version vX.Y.Z --dry-run --ai; require dryRun: true, wouldWrite: false, wouldDownload: false, and all effects.* mutation booleans to be false before treating the plan as non-mutating. Use a pinned --version when the dry-run must avoid the latest-release network lookup.
  2. Session Persistence:

    • Running init and login persists session data inside .config/fin-cli/adapter_state.json.
    • Check if you are authenticated using status before making trading queries.
    • Core JSON state files are written atomically; monitor event mutations use a lock file; audit logs are append-only JSONL files.
    • For long-running agents, preview local log retention with fin-cli maintenance prune --target all --keep 10000 --older-than-days 90 --dry-run=true --ai; apply only with --dry-run=false --confirm=true after reviewing the counts.
  3. Avoid Interactive Prompts:

    • Provide all required flags to prevent the CLI from asking for standard input.
  4. Order Safety:

    • Always preview orders with --dry-run=true --ai before sending.
    • Use capabilities --ai order.buyDryRunTemplate, sellDryRunTemplate, cancelDryRunTemplate, modifyDryRunTemplate, inputValidation, liveApplyTemplateSuffix, and auditTemplate as the source of truth for AI order command composition.
    • Validate order details against order.inputValidation before composing commands; fin-cli also rejects invalid symbols, order numbers, non-positive quantities, unsupported order types, and non-positive limit prices before broker submission.
    • When applying a live order, fill order.liveApplyTemplateSuffix <audit_id> with the dry-run response audit_id; fin-cli validates the preview audit status, action, environment, transaction id, and request body before contacting the broker.
    • Live order, cancel, and modify commands are blocked unless --confirm=true is provided.
    • Do not add --confirm=true unless the user explicitly requested the live broker action and all order details are present.
    • Use returned audit_id values to connect order previews and submissions to fin-cli order audit --id <audit_id> --ai; check summary.statusCounts, summary.latestPreviewAuditId, summary.latestSubmittedAuditId, and logIntegrity.malformedLines; narrow broader investigations with --status preview|blocked|submitted|failed, --action buy|sell|cancel|modify, and --symbol <code>.
  5. Monitoring Event Hooks:

    • Use fin-cli monitor hook register as the standard setup path. Do not hardcode Hermes webhook URLs or secrets.
    • Use capabilities --ai monitor.hookRegistration.registerDryRunTemplate, registerApplyTemplate, removeDryRunTemplate, testTemplate, and listTemplate as the source of truth for hook lifecycle commands. Fill only placeholders such as <discord-channel-id> and <symbol>.
    • Default profile: hermes-helper; default route: fin-cli-monitor; event type: alert_triggered.
    • Preview registration with fin-cli monitor hook register --dry-run=true --profile hermes-helper --route fin-cli-monitor --events alert_triggered --deliver discord --deliver-chat-id "<discord-channel-id>" --ai before creating the Hermes subscription.
    • For --deliver discord, always provide --deliver-chat-id; dry-run validates this locally before invoking Hermes. Route and event names are also validated locally, so treat validation errors as input bugs to fix before retrying.
    • In hook register/remove dry-run output, check dryRun, wouldWrite, subscription.effects.hermesSubscription, subscription.effects.localHookConfig, subscription.effects.mutatesHermes, and subscription.effects.mutatesLocalConfig; dry-run must report dryRun: true, wouldWrite: false, and both mutation booleans as false.
    • Register and connect a Hermes webhook with fin-cli monitor hook register --profile hermes-helper --route fin-cli-monitor --events alert_triggered --deliver discord --deliver-chat-id "<discord-channel-id>" --timeout-ms 5000 --retries 2 --retry-delay-ms 500 --ai; fin-cli accepts Hermes text or JSON subscription output. Verify dryRun: false, wouldWrite: true, and the returned sanitized subscription/hook objects instead of reading or storing the raw webhook URL/secret.
    • Preview low-level local hook config changes with fin-cli monitor hook set --url "<webhook-url>" --secret "<secret>" --dry-run=true --ai or fin-cli monitor hook clear --dry-run=true --ai; dry-run must not write or delete local hook config. Webhook URLs must be valid http:// or https:// URLs.
    • Validate delivery with fin-cli monitor hook test --ai. Check capabilities --ai monitor.hookTest.resultFields, hookResultFields, and effectFields; hook test sends a synthetic alert and appends delivery history, so expect dryRun: false, wouldWrite: true, and inspect hook_result.failureCategory / hook_result.retryable on failure before retrying or repairing configuration.
    • Applied hook configuration changes return audit_id values. Use fin-cli monitor hook audit --id <audit_id> --ai for exact hook lifecycle trace lookup, or fin-cli monitor hook audit --action register --status applied --profile hermes-helper --route fin-cli-monitor --ai for broader investigations. Check summary.actionCounts, summary.statusCounts, summary.latestFailedAuditId, and logIntegrity.malformedLines. If hook registration/removal fails, inspect fin-cli monitor hook audit --status failed --ai; failed audit records must remain sanitized and must not expose raw webhook URLs or secrets.
    • Inspect the active hook with fin-cli monitor hook show --ai before testing or replaying delivery. Check configured, source (env:webhook, env:command, file, or none), envOverride, fileExists, disabled, invalid, sanitized hook, and fingerprint fields. If invalid: true, re-register or clear the hook instead of editing event_hook.json manually.
    • Inspect recent delivery results with fin-cli monitor hook history --limit 20 --ai; delivery history must not contain webhook secrets, common token/password/authorization/API-key values, or unbounded response bodies. Check capabilities --ai monitor.hookHistory.recordFields, failureCategories, and retryableHttpStatuses, then inspect summary.statusCounts, summary.failureCategoryCounts, summary.retryableFailedCount, summary.failureRate, summary.latestFailedDeliveryId, summary.latestFailedReplayDryRunCommand, summary.latestRetryableFailedReplayDryRunCommand, failureCategory, retryable, retryAfterMs on rate-limited webhook records, and logIntegrity.malformedLines; malformed JSONL delivery records are ignored so one corrupt line does not block history or replay of valid records.
    • Narrow hook history with --status failed, --failure-category http_retryable, --retryable true, --event alert_triggered, --event-id <event-id>, --correlation-id <correlation-id>, --delivery-id <delivery-id>, --replay-of <delivery-id>, --symbol <code>, --since <ISO timestamp>, and/or --until <ISO timestamp> before replaying.
    • Check fin-cli capabilities --ai monitor.hookReplay.resultFields, batchFilterFields, failureCategories, effectFields, dryRunEffects, and emptyBatchEffects before automating replay decisions.
    • For failed deliveries, preview replay with fin-cli monitor hook replay --latest-failed=true --dry-run=true --ai, then apply fin-cli monitor hook replay --latest-failed=true --ai or replay a specific delivery with --id <delivery-id>. In replay dry-run output, verify wouldWrite: false and effects.mutatesHookTarget: false; applying replay sends the stored payload again and appends a new delivery history record.
    • When multiple deliveries failed, preview a filtered batch with fin-cli monitor hook replay --batch=true --status failed --failure-category http_retryable --retryable true --event alert_triggered --correlation-id <correlation-id> --symbol <code> --since <ISO timestamp> --limit 20 --dry-run=true --ai; apply only after reviewing the selected delivery count, filters, replayedCount, failedCount, unreplayableCount, and unreplayableDeliveryIds. Add --dedupe-correlation=true when replaying broad batches so only the newest selected delivery per alert correlation is resent. Use --replay-of <delivery-id> to inspect or replay records created from a specific original delivery.
    • Manage Hermes subscriptions with fin-cli monitor hook list --profile hermes-helper --ai and preview removal with fin-cli monitor hook remove --profile hermes-helper --route fin-cli-monitor --dry-run=true --ai before applying without --dry-run=true.
    • Manage price alert events separately with fin-cli monitor event add/update/test/list/pause/resume/export/import/audit/rollback/template/remove --ai.
    • Start reusable alert design from capabilities --ai monitor.eventTemplateCatalog or fin-cli monitor event template list --ai; narrow candidates with --condition-type, --mode, --condition-mode, and --has-filter true|false, then inspect a recipe with fin-cli monitor event template show --name price-breakout --ai, --name percent-breakout, or --name krx-session-breakout; templates return required flags, defaults, conditions, and an example command.
    • Use capabilities --ai monitor.eventAutomation.addDryRunTemplate, templateApplyDryRunTemplate, and testTemplate with monitor.eventConditionCatalog[].exampleValue and testExampleArgs when composing event add/update dry-runs, template apply dry-runs, or deterministic monitor event test commands.
    • Prefer fin-cli monitor event template apply --name price-breakout --symbol 005930 --target-price 71500 --id agent:005930:breakout --dry-run=true --ai before applying without --dry-run=true; use --name krx-session-breakout when the alert should include weekday 09:00-15:30 KRX session filters by default. Apply maps template placeholders to the concrete monitor event add flags and returns postApplyTestCommand; run that command after applying the event to verify test_input_coverage.deterministic.
    • Prefer a stable monitor event add --id <agent-owned-id> when recreating known alerts; IDs must be unique and match [A-Za-z0-9][A-Za-z0-9_.:-]*.
    • Preview event mutations with monitor event add/update/remove/pause/resume ... --dry-run=true --ai; dry-run returns status: "validated", wouldWrite: false, and audit_id: null without changing event state or audit logs. Applied event mutations return audit_id values that link directly to fin-cli monitor event audit --id <audit_id> --ai records.
    • Narrow event lists with --id <event-id>, --id-prefix <agent-owned-prefix>, --status active|paused, --mode once|repeat, --condition-type <type>, --symbol <code>, --runnable true|false, --started true|false, --starts-after <ISO timestamp>, --starts-before <ISO timestamp>, --expired true|false, --expires-after <ISO timestamp>, and/or --expires-before <ISO timestamp>; narrow event audits with --action, --event-id, --symbol, and --status.
    • Check monitor event list --ai summary for active/paused/repeat/started/expired/exhausted/runnable/notRunnable counts and each event's runnable plus runnableBlockers (paused, status_not_active, not_started, expired, exhausted) before mutating events. If parseError or invalidEntries is non-zero, follow doctor --ai review-monitor-event-store, inspect with fin-cli monitor event list --ai, and repair or restore events.json; mutation commands intentionally refuse to write over an invalid event store.
    • Use update to adjust an existing event without deleting trigger history. Condition flags passed to update merge by condition type unless --replace-conditions=true is provided.
    • Use test --id "<event-id>" --price <price> --ai before starting or changing the daemon when validating complex conditions; it does not mutate event state.
    • Inspect monitor event test --ai reason, condition_results, and test_input_coverage before changing an event: reasons include triggered, triggered_final, conditions_not_matched, filters_not_matched, cooldown, not_started, expired, and exhausted. Use capabilities --ai monitor.eventTestInputCatalog to map required test flags to explicit CLI inputs or implicit event-state sources. Use each condition result's formattedThreshold to verify time/day filters without decoding numeric thresholds. test_input_coverage.deterministic should be true before trusting a complex simulation; missing inputs name the exact flags to add.
    • If overriding simulation time, pass --timestamp as integer Unix timestamp seconds only.
    • For percent or amount conditions, include --ref-price <price> in monitor event test when the event definition does not already pin a reference price.
    • For price/percent crossing conditions, include --previous-price <price> in monitor event test so the simulated cross does not depend on the event file's last observed tick; for volume crossing conditions, include --previous-volume <volume> with the current --volume <volume>.
    • Use capabilities --ai monitor.eventAutomation.exportTemplate, importDryRunTemplate, and importReplaceDryRunTemplate, then run export --file <path> --ai and import --file <path> --replace=true --dry-run=true --ai before import --file <path> --replace=true --ai to preview added/updated/removed/unchanged event ids when backing up or reproducing event definitions across agent environments. monitor event export --ai returns wouldWrite and effects.localBackupFile; it is read-only only when --file is omitted, while --file writes a local backup file. monitor event import --ai returns effects.localEventStore, effects.eventAuditLog, effects.mutatesLocalEventStore, and effects.mutatesEventAuditLog; dry-run leaves the event store and event audit log unchanged.
    • Import payloads must not contain duplicate event ids; fix the source file instead of relying on overwrite order.
    • Imported event ids must use only [A-Za-z0-9_.:-], start with an alphanumeric character, and be at most 128 characters; unknown enum values are rejected.
    • Use audit --limit 20 --ai, check summary.actionCounts, summary.statusCounts, summary.latestAuditId, summary.latestAppliedAuditId, and logIntegrity.malformedLines, then run rollback --audit-id <audit-id> --dry-run=true --ai before applying rollback --audit-id <audit-id> --ai to recover from a bad add/update/remove/import. Malformed audit JSONL lines are skipped so valid records remain inspectable. Applied rollback returns a new audit_id for the rollback audit record. If rollback reports a conflict, inspect the newer event changes, then use rollback --audit-id <audit-id> --force=true --dry-run=true --ai to review conflicts, conflictCount, and forceOverridesConflicts before intentionally applying with --force=true.
    • Prefer pause over remove when the user wants to stop alerts temporarily while preserving the event definition.
    • Event conditions support percent movement (--trigger-up, --trigger-down), percent crossing (--trigger-cross-up, --trigger-cross-down), absolute price (--price-above, --price-below), price crossing (--price-cross-above, --price-cross-below), absolute amount from reference (--amount-up, --amount-down), cumulative volume (--volume-above, --volume-below), volume crossing (--volume-cross-above, --volume-cross-below), local time windows (--time-after HH:MM, --time-before HH:MM), local day filters (--days mon,tue,wed,thu,fri), --condition-mode any|all, --mode once|repeat, --cooldown-sec, --max-trigger-count <n>, --starts-at <ISO timestamp>, and --expires-at <ISO timestamp>. Prefer capabilities --ai monitor.eventConditionCatalog as the authoritative flag/role/test-input map.
    • Use --starts-at to pre-register future alerts, --expires-at for one-off campaign or session-specific alerts, and --max-trigger-count to cap noisy repeat alerts; remove them with monitor event update --id <event-id> --clear-starts-at=true --clear-expires-at=true --clear-max-trigger-count=true --ai.
    • After reviewing an exhausted or noisy repeat event, use monitor event update --id <event-id> --reset-trigger-count=true --reset-observed-state=true --ai to keep the definition while clearing its trigger count, last trigger timestamp, and crossing-condition observation state.
    • Time window and day conditions are filters, not standalone alert triggers; include at least one price/percent/amount/volume/crossing condition.
    • Use --condition-mode all when the user wants a combined price/percent/amount/volume filter such as "price above 71000 and volume above 1,000,000 during market hours"; omit it or use any for independent alert thresholds.
    • When a monitor alert triggers, the event JSON is POSTed to the webhook with X-Hub-Signature-256, X-Fin-Cli-Delivery-Id, X-Fin-Cli-Correlation-Id, and X-Fin-Cli-Event-Id; command hooks receive the equivalent FIN_CLI_* environment variables.
    • Webhook delivery retries network errors, timeouts, HTTP 429 responses, and HTTP 5xx responses. Retry-After is honored for retryable webhook responses when present. Other HTTP 4xx responses indicate hook configuration/authentication errors and are not retried.
    • Runtime overrides are supported with FIN_CLI_HERMES_WEBHOOK_URL / FIN_CLI_HERMES_WEBHOOK_SECRET or FIN_CLI_EVENT_HOOK_URL / FIN_CLI_EVENT_HOOK_SECRET.
    • Delivery policy overrides are supported with FIN_CLI_HERMES_WEBHOOK_TIMEOUT_MS, FIN_CLI_HERMES_WEBHOOK_RETRIES, FIN_CLI_HERMES_WEBHOOK_RETRY_DELAY_MS or the equivalent FIN_CLI_EVENT_HOOK_* variables.
    • For full operational steps, read docs/hermes-agent.md.