asoftime 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- adapters/__init__.py +0 -0
- adapters/antigravity/__init__.py +0 -0
- adapters/antigravity/asof_antigravity_orchestrator.py +362 -0
- adapters/antigravity/install.py +105 -0
- adapters/claude_code/__init__.py +0 -0
- adapters/claude_code/install.py +152 -0
- adapters/claude_code/post_tool.py +50 -0
- adapters/claude_code/session_init.py +79 -0
- adapters/claude_code/watch.py +75 -0
- adapters/generic/__init__.py +0 -0
- adapters/generic/examples/anthropic_sdk_wrapper.py +115 -0
- adapters/generic/examples/crewai_step.py +78 -0
- adapters/generic/examples/langgraph_node.py +79 -0
- asof_core/__init__.py +16 -0
- asof_core/cli.py +235 -0
- asof_core/cutoffs.py +133 -0
- asof_core/hooks/__init__.py +29 -0
- asof_core/hooks/post_tool.py +159 -0
- asof_core/hooks/session_init.py +118 -0
- asof_core/hooks/watch.py +193 -0
- asof_core/output.py +240 -0
- asof_core/patterns/__init__.py +112 -0
- asof_core/patterns/domains/__init__.py +25 -0
- asof_core/patterns/domains/crypto.py +28 -0
- asof_core/patterns/domains/devops.py +31 -0
- asof_core/patterns/domains/finance.py +33 -0
- asof_core/patterns/domains/news.py +28 -0
- asof_core/patterns/domains/sports.py +27 -0
- asof_core/patterns/domains/stocks.py +32 -0
- asof_core/patterns/domains/travel.py +32 -0
- asof_core/patterns/domains/weather.py +24 -0
- asof_core/patterns/high_confidence.py +61 -0
- asof_core/patterns/medium_confidence.py +69 -0
- asof_core/provenance.py +205 -0
- asof_core/query.py +294 -0
- asof_core/stat.py +233 -0
- asof_core/timestamps.py +266 -0
- asof_core/url_freshness.py +152 -0
- asof_core/version.py +61 -0
- asof_core/watchlist.py +171 -0
- asoftime-0.1.0.dist-info/METADATA +208 -0
- asoftime-0.1.0.dist-info/RECORD +46 -0
- asoftime-0.1.0.dist-info/WHEEL +5 -0
- asoftime-0.1.0.dist-info/entry_points.txt +2 -0
- asoftime-0.1.0.dist-info/licenses/LICENSE +21 -0
- asoftime-0.1.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Claude Code SessionStart hook entry.
|
|
2
|
+
|
|
3
|
+
Invoked by Claude Code at session begin. Reads session metadata from
|
|
4
|
+
the JSONL transcript, looks up model cutoff, emits the directive block
|
|
5
|
+
to stdout (which Claude Code injects as a system-reminder).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
# Force UTF-8 stdout so non-ASCII characters survive the hook pipe
|
|
16
|
+
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8",
|
|
17
|
+
errors="replace", line_buffering=True)
|
|
18
|
+
|
|
19
|
+
from asof_core.hooks import session_init
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _read_session_event() -> dict:
|
|
23
|
+
"""Read the session event JSON from stdin. Returns {} on failure."""
|
|
24
|
+
try:
|
|
25
|
+
raw = sys.stdin.read()
|
|
26
|
+
if not raw:
|
|
27
|
+
return {}
|
|
28
|
+
d = json.loads(raw)
|
|
29
|
+
return d if isinstance(d, dict) else {}
|
|
30
|
+
except (json.JSONDecodeError, ValueError, OSError):
|
|
31
|
+
return {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _find_model_from_transcript() -> str | None:
|
|
35
|
+
"""Walk the latest session JSONL and return the model ID from any
|
|
36
|
+
message. Claude Code records the model in every assistant message."""
|
|
37
|
+
try:
|
|
38
|
+
proj_dir = Path.home() / ".claude" / "projects"
|
|
39
|
+
# Project dirs have hashed names; find the latest by mtime
|
|
40
|
+
candidates = []
|
|
41
|
+
if proj_dir.is_dir():
|
|
42
|
+
for d in proj_dir.iterdir():
|
|
43
|
+
if d.is_dir():
|
|
44
|
+
jsonls = list(d.glob("*.jsonl"))
|
|
45
|
+
if jsonls:
|
|
46
|
+
candidates.extend(jsonls)
|
|
47
|
+
if not candidates:
|
|
48
|
+
return None
|
|
49
|
+
latest = max(candidates, key=lambda p: p.stat().st_mtime)
|
|
50
|
+
with latest.open(encoding="utf-8") as f:
|
|
51
|
+
for line in f:
|
|
52
|
+
try:
|
|
53
|
+
d = json.loads(line)
|
|
54
|
+
except (json.JSONDecodeError, ValueError):
|
|
55
|
+
continue
|
|
56
|
+
msg = d.get("message") if isinstance(d.get("message"), dict) else None
|
|
57
|
+
if msg and msg.get("model"):
|
|
58
|
+
return msg["model"]
|
|
59
|
+
return None
|
|
60
|
+
except OSError:
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def main() -> int:
|
|
65
|
+
event = _read_session_event()
|
|
66
|
+
session_id = event.get("session_id") or "unknown-session"
|
|
67
|
+
model_id = event.get("model") or _find_model_from_transcript()
|
|
68
|
+
|
|
69
|
+
out = session_init(
|
|
70
|
+
model_id=model_id,
|
|
71
|
+
session_id=session_id,
|
|
72
|
+
now=datetime.now(timezone.utc),
|
|
73
|
+
)
|
|
74
|
+
print(out)
|
|
75
|
+
return 0
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == "__main__":
|
|
79
|
+
sys.exit(main())
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Claude Code UserPromptSubmit hook entry.
|
|
2
|
+
|
|
3
|
+
Invoked by Claude Code before every model response. Reads the event
|
|
4
|
+
JSON (which includes the user's prompt text), runs the watch function,
|
|
5
|
+
emits the adaptive verdict block to stdout.
|
|
6
|
+
|
|
7
|
+
Empty stdout means no signal — Claude Code surfaces nothing.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
# Force UTF-8 stdout
|
|
18
|
+
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8",
|
|
19
|
+
errors="replace", line_buffering=True)
|
|
20
|
+
|
|
21
|
+
from asof_core.hooks import watch
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _load_config() -> dict:
|
|
25
|
+
"""Load AsOf config from ~/.asof/config.json. Returns {} if missing
|
|
26
|
+
or invalid (default behavior takes over)."""
|
|
27
|
+
try:
|
|
28
|
+
config_path = Path.home() / ".asof" / "config.json"
|
|
29
|
+
if not config_path.is_file():
|
|
30
|
+
return {}
|
|
31
|
+
with config_path.open(encoding="utf-8") as f:
|
|
32
|
+
data = json.load(f)
|
|
33
|
+
return data if isinstance(data, dict) else {}
|
|
34
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
35
|
+
return {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main() -> int:
|
|
39
|
+
try:
|
|
40
|
+
raw = sys.stdin.read()
|
|
41
|
+
event = json.loads(raw) if raw else {}
|
|
42
|
+
except (json.JSONDecodeError, ValueError, OSError):
|
|
43
|
+
event = {}
|
|
44
|
+
|
|
45
|
+
session_id = event.get("session_id") or "unknown-session"
|
|
46
|
+
prompt_text = event.get("prompt") or ""
|
|
47
|
+
if isinstance(prompt_text, list):
|
|
48
|
+
# Multi-part prompts (Claude Code can send arrays of content blocks)
|
|
49
|
+
parts = []
|
|
50
|
+
for p in prompt_text:
|
|
51
|
+
if isinstance(p, dict) and p.get("type") == "text":
|
|
52
|
+
parts.append(p.get("text") or "")
|
|
53
|
+
elif isinstance(p, str):
|
|
54
|
+
parts.append(p)
|
|
55
|
+
prompt_text = "\n".join(parts)
|
|
56
|
+
|
|
57
|
+
config = _load_config()
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
out = watch(
|
|
61
|
+
session_id=session_id,
|
|
62
|
+
prompt_text=prompt_text,
|
|
63
|
+
config=config,
|
|
64
|
+
now=datetime.now(timezone.utc),
|
|
65
|
+
)
|
|
66
|
+
if out:
|
|
67
|
+
print(out)
|
|
68
|
+
except Exception:
|
|
69
|
+
# Silent failure — never break the substrate
|
|
70
|
+
pass
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
sys.exit(main())
|
|
File without changes
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Direct Anthropic SDK reference integration for AsOf.
|
|
2
|
+
|
|
3
|
+
Wraps a `messages.create` call to:
|
|
4
|
+
1. Inject session_init output as the first system message on session start
|
|
5
|
+
2. Inject the watch verdict block before each turn (if non-empty)
|
|
6
|
+
3. Log tool calls via post_tool after each tool use
|
|
7
|
+
|
|
8
|
+
Use:
|
|
9
|
+
from anthropic import Anthropic
|
|
10
|
+
from asof_anthropic_wrapper import AsOfClient
|
|
11
|
+
|
|
12
|
+
client = AsOfClient(
|
|
13
|
+
Anthropic(),
|
|
14
|
+
session_id="my-session",
|
|
15
|
+
model="claude-opus-4-7",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
response = client.create_message(
|
|
19
|
+
prompt="What's the current price of AAPL?",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
The wrapper handles the AsOf bookkeeping behind the scenes.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import uuid
|
|
27
|
+
from datetime import datetime, timezone
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from asof_core.hooks import session_init, post_tool, watch
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AsOfClient:
|
|
34
|
+
"""Thin wrapper over an Anthropic client with AsOf integration.
|
|
35
|
+
|
|
36
|
+
Stateful: tracks whether session_init has been called for the
|
|
37
|
+
current session_id, and injects the directive only once.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, anthropic_client: Any, *, session_id: str = None, model: str = None):
|
|
41
|
+
self.client = anthropic_client
|
|
42
|
+
self.session_id = session_id or str(uuid.uuid4())
|
|
43
|
+
self.model = model or "claude-opus-4-7"
|
|
44
|
+
self._init_fired = False
|
|
45
|
+
self._conversation_messages: list[dict] = []
|
|
46
|
+
|
|
47
|
+
def create_message(self, prompt: str, **kwargs) -> Any:
|
|
48
|
+
"""Send a message with AsOf temporal context injected.
|
|
49
|
+
|
|
50
|
+
`kwargs` pass through to the underlying client.messages.create.
|
|
51
|
+
"""
|
|
52
|
+
now = datetime.now(timezone.utc)
|
|
53
|
+
|
|
54
|
+
# First call this session — inject session_init as system content
|
|
55
|
+
system_parts: list[str] = []
|
|
56
|
+
if not self._init_fired:
|
|
57
|
+
system_parts.append(session_init(
|
|
58
|
+
model_id=self.model,
|
|
59
|
+
session_id=self.session_id,
|
|
60
|
+
now=now,
|
|
61
|
+
))
|
|
62
|
+
self._init_fired = True
|
|
63
|
+
|
|
64
|
+
# Per-turn watch
|
|
65
|
+
watch_block = watch(
|
|
66
|
+
session_id=self.session_id,
|
|
67
|
+
prompt_text=prompt,
|
|
68
|
+
now=now,
|
|
69
|
+
)
|
|
70
|
+
if watch_block:
|
|
71
|
+
system_parts.append(watch_block)
|
|
72
|
+
|
|
73
|
+
# Merge with any user-provided system content
|
|
74
|
+
existing_system = kwargs.pop("system", "")
|
|
75
|
+
if existing_system and isinstance(existing_system, str):
|
|
76
|
+
full_system = "\n\n".join([*system_parts, existing_system])
|
|
77
|
+
else:
|
|
78
|
+
full_system = "\n\n".join(system_parts)
|
|
79
|
+
|
|
80
|
+
self._conversation_messages.append({"role": "user", "content": prompt})
|
|
81
|
+
|
|
82
|
+
response = self.client.messages.create(
|
|
83
|
+
model=self.model,
|
|
84
|
+
system=full_system if full_system else None,
|
|
85
|
+
messages=self._conversation_messages,
|
|
86
|
+
**kwargs,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# Extract assistant response and log any tool uses
|
|
90
|
+
assistant_content = []
|
|
91
|
+
for block in response.content:
|
|
92
|
+
if hasattr(block, "type"):
|
|
93
|
+
if block.type == "text":
|
|
94
|
+
assistant_content.append({"type": "text", "text": block.text})
|
|
95
|
+
elif block.type == "tool_use":
|
|
96
|
+
assistant_content.append({
|
|
97
|
+
"type": "tool_use",
|
|
98
|
+
"id": block.id,
|
|
99
|
+
"name": block.name,
|
|
100
|
+
"input": block.input,
|
|
101
|
+
})
|
|
102
|
+
post_tool(
|
|
103
|
+
session_id=self.session_id,
|
|
104
|
+
tool_name=block.name,
|
|
105
|
+
tool_input=block.input,
|
|
106
|
+
now=datetime.now(timezone.utc),
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if assistant_content:
|
|
110
|
+
self._conversation_messages.append({
|
|
111
|
+
"role": "assistant",
|
|
112
|
+
"content": assistant_content,
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
return response
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""CrewAI reference integration for AsOf.
|
|
2
|
+
|
|
3
|
+
Wraps an agent's `execute` method to inject temporal context before
|
|
4
|
+
each call. The agent sees the AsOf block as part of its task description.
|
|
5
|
+
|
|
6
|
+
Use:
|
|
7
|
+
from crewai import Agent, Task
|
|
8
|
+
from asof_core_examples.crewai_step import wrap_agent_with_asof
|
|
9
|
+
|
|
10
|
+
analyst = Agent(role="Financial Analyst", ...)
|
|
11
|
+
analyst = wrap_agent_with_asof(analyst, session_id="my-session")
|
|
12
|
+
|
|
13
|
+
task = Task(description="Analyze the Q3 2025 earnings", agent=analyst)
|
|
14
|
+
crew = Crew(agents=[analyst], tasks=[task])
|
|
15
|
+
crew.kickoff()
|
|
16
|
+
|
|
17
|
+
The wrapper injects AsOf's directive + per-turn watch into the task
|
|
18
|
+
description automatically.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from asof_core.hooks import session_init, post_tool, watch
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_SESSION_INIT_FIRED: set[str] = set()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def wrap_agent_with_asof(agent: Any, *, session_id: str, model_id: str = None) -> Any:
|
|
32
|
+
"""Monkey-patch an agent's `execute_task` (CrewAI 0.x+) to inject
|
|
33
|
+
AsOf temporal context into each task description.
|
|
34
|
+
|
|
35
|
+
Best-effort wrapping. If the underlying CrewAI API changes, adjust
|
|
36
|
+
the wrapped method name.
|
|
37
|
+
"""
|
|
38
|
+
if not hasattr(agent, "execute_task"):
|
|
39
|
+
raise AttributeError(
|
|
40
|
+
"Agent does not have execute_task method. "
|
|
41
|
+
"Check CrewAI version compatibility."
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
original = agent.execute_task
|
|
45
|
+
|
|
46
|
+
def wrapped(task, *args, **kwargs):
|
|
47
|
+
now = datetime.now(timezone.utc)
|
|
48
|
+
|
|
49
|
+
# Session-init fires once per session_id
|
|
50
|
+
if session_id not in _SESSION_INIT_FIRED and model_id:
|
|
51
|
+
init_block = session_init(model_id=model_id, session_id=session_id, now=now)
|
|
52
|
+
_SESSION_INIT_FIRED.add(session_id)
|
|
53
|
+
task.description = init_block + "\n\n" + (task.description or "")
|
|
54
|
+
|
|
55
|
+
# Per-task watch (acts like UserPromptSubmit)
|
|
56
|
+
watch_block = watch(
|
|
57
|
+
session_id=session_id,
|
|
58
|
+
prompt_text=task.description or "",
|
|
59
|
+
now=now,
|
|
60
|
+
)
|
|
61
|
+
if watch_block:
|
|
62
|
+
task.description = watch_block + "\n\n" + (task.description or "")
|
|
63
|
+
|
|
64
|
+
return original(task, *args, **kwargs)
|
|
65
|
+
|
|
66
|
+
agent.execute_task = wrapped
|
|
67
|
+
return agent
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def log_tool_call(*, session_id: str, tool_name: str, tool_input: dict) -> None:
|
|
71
|
+
"""Helper for CrewAI tools — call this from your tool's run method
|
|
72
|
+
so AsOf can track the call for freshness verdicts."""
|
|
73
|
+
post_tool(
|
|
74
|
+
session_id=session_id,
|
|
75
|
+
tool_name=tool_name,
|
|
76
|
+
tool_input=tool_input,
|
|
77
|
+
now=datetime.now(timezone.utc),
|
|
78
|
+
)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""LangGraph reference integration for AsOf.
|
|
2
|
+
|
|
3
|
+
Drop this node into your graph immediately before the model-call node.
|
|
4
|
+
It produces the time-aware system content that should be prepended to
|
|
5
|
+
the model's message list.
|
|
6
|
+
|
|
7
|
+
Example graph:
|
|
8
|
+
graph = StateGraph(AgentState)
|
|
9
|
+
graph.add_node("asof", asof_node)
|
|
10
|
+
graph.add_node("plan", plan_node)
|
|
11
|
+
graph.add_node("act", act_node)
|
|
12
|
+
graph.add_edge("asof", "plan")
|
|
13
|
+
graph.add_edge("plan", "act")
|
|
14
|
+
graph.set_entry_point("asof")
|
|
15
|
+
|
|
16
|
+
The AsOf node enriches the state with a `temporal_context` field. The
|
|
17
|
+
downstream plan/act nodes prepend it to the model's system message.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from datetime import datetime, timezone
|
|
22
|
+
from typing import Any, Dict
|
|
23
|
+
|
|
24
|
+
from asof_core.hooks import session_init, watch
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def asof_node(state: Dict[str, Any]) -> Dict[str, Any]:
|
|
28
|
+
"""LangGraph node that produces temporal context.
|
|
29
|
+
|
|
30
|
+
Expected state fields:
|
|
31
|
+
session_id: str — graph session identifier
|
|
32
|
+
model_id: str — the model being used
|
|
33
|
+
user_prompt: str — the current user message
|
|
34
|
+
is_first_turn: bool — True only on the first invocation per session
|
|
35
|
+
|
|
36
|
+
Returns updated state with `temporal_context` field populated.
|
|
37
|
+
"""
|
|
38
|
+
session_id = state.get("session_id", "langgraph-default")
|
|
39
|
+
model_id = state.get("model_id")
|
|
40
|
+
user_prompt = state.get("user_prompt", "")
|
|
41
|
+
is_first_turn = state.get("is_first_turn", False)
|
|
42
|
+
now = datetime.now(timezone.utc)
|
|
43
|
+
|
|
44
|
+
pieces: list[str] = []
|
|
45
|
+
|
|
46
|
+
if is_first_turn and model_id:
|
|
47
|
+
pieces.append(session_init(model_id=model_id, session_id=session_id, now=now))
|
|
48
|
+
|
|
49
|
+
block = watch(session_id=session_id, prompt_text=user_prompt, now=now)
|
|
50
|
+
if block:
|
|
51
|
+
pieces.append(block)
|
|
52
|
+
|
|
53
|
+
state["temporal_context"] = "\n".join(pieces)
|
|
54
|
+
return state
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def post_tool_node(state: Dict[str, Any]) -> Dict[str, Any]:
|
|
58
|
+
"""LangGraph node to run after tool calls. Logs the tool use into
|
|
59
|
+
AsOf's session-scoped log so the next `asof_node` invocation can
|
|
60
|
+
compute freshness verdicts.
|
|
61
|
+
|
|
62
|
+
Expected state fields (in addition to those used by asof_node):
|
|
63
|
+
last_tool_name: str
|
|
64
|
+
last_tool_input: dict
|
|
65
|
+
"""
|
|
66
|
+
from asof_core.hooks import post_tool
|
|
67
|
+
|
|
68
|
+
session_id = state.get("session_id", "langgraph-default")
|
|
69
|
+
tool_name = state.get("last_tool_name")
|
|
70
|
+
tool_input = state.get("last_tool_input", {})
|
|
71
|
+
|
|
72
|
+
if tool_name:
|
|
73
|
+
post_tool(
|
|
74
|
+
session_id=session_id,
|
|
75
|
+
tool_name=tool_name,
|
|
76
|
+
tool_input=tool_input,
|
|
77
|
+
now=datetime.now(timezone.utc),
|
|
78
|
+
)
|
|
79
|
+
return state
|
asof_core/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""AsOf — temporal-awareness skill for tool-using LLMs.
|
|
2
|
+
|
|
3
|
+
A per-turn hook plus a teaching prose layer. Hook does the computation
|
|
4
|
+
in Python (so the model never does unreliable date arithmetic in chat).
|
|
5
|
+
Prose teaches the model how to interpret hook output.
|
|
6
|
+
|
|
7
|
+
Target substrates: Claude Code, Antigravity (Gemini), generic harnesses.
|
|
8
|
+
|
|
9
|
+
See: docs/design.md for the full specification.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from asof_core.version import SCHEMA_VERSION, MIN_PROSE_VERSION
|
|
14
|
+
|
|
15
|
+
__all__ = ["SCHEMA_VERSION", "MIN_PROSE_VERSION"]
|
|
16
|
+
__version__ = "0.1.0"
|
asof_core/cli.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""AsOf CLI — install, config, check, query.
|
|
2
|
+
|
|
3
|
+
Entry point registered in pyproject.toml as `asof`. Routes subcommands
|
|
4
|
+
to the right adapter or core module.
|
|
5
|
+
|
|
6
|
+
Usage:
|
|
7
|
+
asof install [--adapter claude_code|antigravity|generic]
|
|
8
|
+
asof check
|
|
9
|
+
asof config [get|set|add-domain|remove-domain] [args]
|
|
10
|
+
asof query <target>
|
|
11
|
+
asof --version
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
CONFIG_DIR = Path.home() / ".asof"
|
|
23
|
+
CONFIG_PATH = CONFIG_DIR / "config.json"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _detect_substrate() -> str | None:
|
|
27
|
+
"""Heuristic substrate detection.
|
|
28
|
+
|
|
29
|
+
Returns "claude_code" if ~/.claude/settings.json exists,
|
|
30
|
+
"antigravity" if ~/.gemini/config/hooks.json exists, else None.
|
|
31
|
+
"""
|
|
32
|
+
if (Path.home() / ".claude" / "settings.json").is_file() or (Path.home() / ".claude").is_dir():
|
|
33
|
+
return "claude_code"
|
|
34
|
+
if (Path.home() / ".gemini" / "config" / "hooks.json").is_file() or (Path.home() / ".gemini").is_dir():
|
|
35
|
+
return "antigravity"
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _load_config() -> dict:
|
|
40
|
+
if not CONFIG_PATH.is_file():
|
|
41
|
+
return {}
|
|
42
|
+
try:
|
|
43
|
+
with CONFIG_PATH.open(encoding="utf-8") as f:
|
|
44
|
+
return json.load(f)
|
|
45
|
+
except (OSError, json.JSONDecodeError):
|
|
46
|
+
return {}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _save_config(config: dict) -> None:
|
|
50
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
with CONFIG_PATH.open("w", encoding="utf-8") as f:
|
|
52
|
+
json.dump(config, f, indent=2)
|
|
53
|
+
f.write("\n")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cmd_install(args: argparse.Namespace) -> int:
|
|
57
|
+
adapter = args.adapter
|
|
58
|
+
if adapter is None:
|
|
59
|
+
adapter = _detect_substrate()
|
|
60
|
+
if adapter is None:
|
|
61
|
+
print("Could not auto-detect substrate. Pass --adapter explicitly:")
|
|
62
|
+
print(" asof install --adapter claude_code")
|
|
63
|
+
print(" asof install --adapter antigravity")
|
|
64
|
+
print(" asof install --adapter generic")
|
|
65
|
+
return 2
|
|
66
|
+
|
|
67
|
+
print(f"Installing AsOf adapter: {adapter}")
|
|
68
|
+
print()
|
|
69
|
+
|
|
70
|
+
# Run the adapter's install module
|
|
71
|
+
try:
|
|
72
|
+
result = subprocess.run(
|
|
73
|
+
[sys.executable, "-m", f"adapters.{adapter}.install"],
|
|
74
|
+
check=False,
|
|
75
|
+
)
|
|
76
|
+
return result.returncode
|
|
77
|
+
except (OSError, FileNotFoundError) as e:
|
|
78
|
+
print(f"FAIL: could not run adapter installer: {e}")
|
|
79
|
+
return 1
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
83
|
+
"""Verify AsOf installation health."""
|
|
84
|
+
print("AsOf installation check:")
|
|
85
|
+
print()
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
import asof_core
|
|
89
|
+
print(f" asof_core importable (v{asof_core.__version__})")
|
|
90
|
+
except ImportError as e:
|
|
91
|
+
print(f" FAIL: asof_core not importable: {e}")
|
|
92
|
+
return 1
|
|
93
|
+
|
|
94
|
+
substrate = _detect_substrate()
|
|
95
|
+
print(f" Detected substrate: {substrate or 'none'}")
|
|
96
|
+
|
|
97
|
+
config = _load_config()
|
|
98
|
+
if config:
|
|
99
|
+
print(f" Config loaded from {CONFIG_PATH}")
|
|
100
|
+
if config.get("patterns", {}).get("domains"):
|
|
101
|
+
print(f" Active domains: {', '.join(config['patterns']['domains'])}")
|
|
102
|
+
else:
|
|
103
|
+
print(f" No config at {CONFIG_PATH} (defaults will be used)")
|
|
104
|
+
|
|
105
|
+
# Try a session-init dry run
|
|
106
|
+
try:
|
|
107
|
+
from asof_core.hooks import session_init
|
|
108
|
+
out = session_init(model_id="claude-opus-4-7", session_id="check")
|
|
109
|
+
if "AsOf v" in out:
|
|
110
|
+
print(f" Session-init dry-run: OK")
|
|
111
|
+
else:
|
|
112
|
+
print(f" WARN: session-init produced unexpected output")
|
|
113
|
+
except Exception as e:
|
|
114
|
+
print(f" FAIL: session-init dry-run errored: {e}")
|
|
115
|
+
return 1
|
|
116
|
+
|
|
117
|
+
print()
|
|
118
|
+
print("Check complete.")
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cmd_config(args: argparse.Namespace) -> int:
|
|
123
|
+
"""View or modify AsOf config."""
|
|
124
|
+
config = _load_config()
|
|
125
|
+
|
|
126
|
+
if args.action == "show" or args.action is None:
|
|
127
|
+
print(json.dumps(config, indent=2))
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
if args.action == "add-domain":
|
|
131
|
+
if not args.value:
|
|
132
|
+
print("Usage: asof config add-domain <name>")
|
|
133
|
+
return 2
|
|
134
|
+
patterns = config.setdefault("patterns", {})
|
|
135
|
+
domains = patterns.setdefault("domains", [])
|
|
136
|
+
if args.value not in domains:
|
|
137
|
+
domains.append(args.value)
|
|
138
|
+
_save_config(config)
|
|
139
|
+
print(f"Added domain: {args.value}")
|
|
140
|
+
else:
|
|
141
|
+
print(f"Domain already active: {args.value}")
|
|
142
|
+
return 0
|
|
143
|
+
|
|
144
|
+
if args.action == "remove-domain":
|
|
145
|
+
if not args.value:
|
|
146
|
+
print("Usage: asof config remove-domain <name>")
|
|
147
|
+
return 2
|
|
148
|
+
domains = config.get("patterns", {}).get("domains", [])
|
|
149
|
+
if args.value in domains:
|
|
150
|
+
domains.remove(args.value)
|
|
151
|
+
_save_config(config)
|
|
152
|
+
print(f"Removed domain: {args.value}")
|
|
153
|
+
else:
|
|
154
|
+
print(f"Domain not currently active: {args.value}")
|
|
155
|
+
return 0
|
|
156
|
+
|
|
157
|
+
if args.action == "set":
|
|
158
|
+
if not args.value:
|
|
159
|
+
print("Usage: asof config set <key>=<value>")
|
|
160
|
+
return 2
|
|
161
|
+
if "=" not in args.value:
|
|
162
|
+
print("Format: key=value (e.g., mode=strict)")
|
|
163
|
+
return 2
|
|
164
|
+
key, _, value = args.value.partition("=")
|
|
165
|
+
config[key] = value
|
|
166
|
+
_save_config(config)
|
|
167
|
+
print(f"Set {key} = {value}")
|
|
168
|
+
return 0
|
|
169
|
+
|
|
170
|
+
print(f"Unknown config action: {args.action}")
|
|
171
|
+
return 2
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def cmd_query(args: argparse.Namespace) -> int:
|
|
175
|
+
"""Run the asof_query oracle on a target."""
|
|
176
|
+
try:
|
|
177
|
+
from asof_core.query import query
|
|
178
|
+
except ImportError as e:
|
|
179
|
+
print(f"FAIL: {e}")
|
|
180
|
+
return 1
|
|
181
|
+
|
|
182
|
+
result = query(args.target)
|
|
183
|
+
print(json.dumps(result, indent=2, default=str))
|
|
184
|
+
return 0
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def cmd_version(args: argparse.Namespace) -> int:
|
|
188
|
+
"""Print version info."""
|
|
189
|
+
try:
|
|
190
|
+
import asof_core
|
|
191
|
+
print(f"asof {asof_core.__version__}")
|
|
192
|
+
print(f"schema {asof_core.SCHEMA_VERSION}")
|
|
193
|
+
print(f"prose-min {asof_core.MIN_PROSE_VERSION}")
|
|
194
|
+
except ImportError as e:
|
|
195
|
+
print(f"FAIL: {e}")
|
|
196
|
+
return 1
|
|
197
|
+
return 0
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def main() -> int:
|
|
201
|
+
parser = argparse.ArgumentParser(
|
|
202
|
+
prog="asof",
|
|
203
|
+
description="AsOf — temporal awareness for tool-using LLMs",
|
|
204
|
+
)
|
|
205
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
206
|
+
|
|
207
|
+
p_install = subparsers.add_parser("install", help="install AsOf adapter")
|
|
208
|
+
p_install.add_argument("--adapter", choices=["claude_code", "antigravity", "generic"], default=None)
|
|
209
|
+
p_install.set_defaults(func=cmd_install)
|
|
210
|
+
|
|
211
|
+
p_check = subparsers.add_parser("check", help="verify installation")
|
|
212
|
+
p_check.set_defaults(func=cmd_check)
|
|
213
|
+
|
|
214
|
+
p_config = subparsers.add_parser("config", help="view or modify config")
|
|
215
|
+
p_config.add_argument("action", nargs="?", choices=["show", "add-domain", "remove-domain", "set"])
|
|
216
|
+
p_config.add_argument("value", nargs="?")
|
|
217
|
+
p_config.set_defaults(func=cmd_config)
|
|
218
|
+
|
|
219
|
+
p_query = subparsers.add_parser("query", help="query the oracle for a target")
|
|
220
|
+
p_query.add_argument("target", help="file path, URL, timestamp, model ID, or text")
|
|
221
|
+
p_query.set_defaults(func=cmd_query)
|
|
222
|
+
|
|
223
|
+
p_version = subparsers.add_parser("version", help="print version info")
|
|
224
|
+
p_version.set_defaults(func=cmd_version)
|
|
225
|
+
|
|
226
|
+
args = parser.parse_args()
|
|
227
|
+
if not args.command:
|
|
228
|
+
parser.print_help()
|
|
229
|
+
return 0
|
|
230
|
+
|
|
231
|
+
return args.func(args)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
if __name__ == "__main__":
|
|
235
|
+
sys.exit(main())
|